views:

83

answers:

5

Hello experts,

O am learning javascript as I analyze existing codes.

In my JS reference book, is searching an single space be "\s"?

But I have came across a code

obj.match(/Kobe Bryant/);

Instead of using \s, it uses the actual space?

Doesn't this suppose to generate an error?

+1  A: 

No. It is perfectly legal to include a literal space in a regex.

However, it's not equivalent - \s will include any whitespace character, including tabs, non-breaking spaces, half-width spaces and other characters, whereas a literal space will only match the regular space character.

SLaks
+2  A: 

\s matches any whitespace character, including tabs etc. Sure you can use a literal space also without problems. Just like you can use [0-9] instead of \d to denote any digit.

Tatu Ulmanen
+1  A: 

In addition to normal spaces, \s matches different kinds of white space characters, including tabs (and possibly newline characters, according to configuration). That said, matching with a normal space is certainly valid, especially in your case where it seems you want to match a name, which is normally separated by a normal space.

Hosam Aly
A: 

Here is a very useful website explaining Regular Expressions in JavaScript:

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

jwhat
This doesn't answer the question.
SLaks
The question was already answered. I was simply providing more resources for further knowledge.
jwhat
+2  A: 

The character class \s does not just contain the space character but also other Unicode white space characters. \s is equivalent to this character class:

[\t\n\v\f\r \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]
Gumbo
+1, probably took you longer than the others to fetch the link :-)
Andy E