Jump to content

'Space remover using js '.replace(/\s/g, '');


w3schoon

Recommended Posts

Nice to be with you everyone! I want to remove spaces using JavaScript and I found this in the web, var a=" W 3 S c h o o l s ";a.replace(/\s/g, ''); output: W3schools I learned that, replace(); - method searches a string for a specified value... http://www.w3schools.com/jsref/jsref_replace.asp \s - Find a whitespace character... http://www.w3schools.com/jsref/jsref_obj_regexp.asp /g - Perform a global match... http://www.w3schools.com/jsref/jsref_obj_regexp.asp '' - Empty string My question is, what is the purpose of "/" before \s? Thank you.

Link to comment
Share on other sites

Regular expressions have the following syntax:

/expression/flags

The two forwards slashes (/) are what makes it a regular expression, just like strings have quotes around them. The expression is the regular expression itself, and the flags are stuff like telling the regular expression to be global ("g" is the modifier, not "/g"). I would recommend disregarding the w3schools regex ref you linked to, it isn't very good.

Edited by callumacrae
  • Like 1
Link to comment
Share on other sites

This is a pretty good link: http://www.regular-expressions.info/
Yep, this is a very good tutorial by the author of "Regular Expressions Cookbook". If you want to know literally everything about regular expressions, buy Mastering Regular Expressions. It will make your head hurt, though.
Link to comment
Share on other sites

fwiw, the power of regex comes in finding patterns in strings. for a simple substitution method like in the OP, a regex might be considered excessive overhead.

Link to comment
Share on other sites

fwiw, the power of regex comes in finding patterns in strings. for a simple substitution method like in the OP, a regex might be considered excessive overhead.
The equivalent string operation would be pretty inefficient, though.
Link to comment
Share on other sites

The equivalent string operation would be pretty inefficient, though.
You mean this?
a.split(" ").join("");

Benchmarking. 1,000,000 iterations:

Split method: 1210msRegExp method: 1504ms
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...