Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regular Expression "Single Space Character"

I am learning javascript and I am analyzing existing codes.

In my JS reference book, it says to search on a single space use "\s"?

But I have came across the code

obj.match(/Kobe Bryant/);

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

Why doesn't this generate an error?

like image 965
Dennis D Avatar asked Mar 11 '10 22:03

Dennis D


People also ask

How do you match a single character with a regular expression?

Match any specific character in a set Use square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

How do you put a space in a regular expression?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

Can a regex have space?

Find Whitespace Using Regular Expressions in Java The most common regex character to find whitespaces are \s and \s+ . The difference between these regex characters is that \s represents a single whitespace character while \s+ represents multiple whitespaces in a string.


4 Answers

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]
like image 54
Gumbo Avatar answered Oct 12 '22 03:10

Gumbo


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.

like image 35
SLaks Avatar answered Oct 12 '22 02:10

SLaks


\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. However, keep in mind that [0-9] is equivalent to \d whereas the literal space is a subset of \s.

like image 37
Tatu Ulmanen Avatar answered Oct 12 '22 02:10

Tatu Ulmanen


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.

like image 45
Hosam Aly Avatar answered Oct 12 '22 02:10

Hosam Aly