js999
js999

Reputation: 2083

Regexp word boundary

Regexp word boundary.

According the Regular_Expressions guide, \b matches a word boundary, such as a space, a newline character, punctuation character or end of string.

I am trying to change the following string from.

"
    abc
"

to

"abc"

I did try the following, but it does not work. Any ideas?

"  abc  ".replace(/\b/,""); 

Upvotes: 2

Views: 777

Answers (3)

Alan Moore
Alan Moore

Reputation: 75262

That description of word boundaries is badly written (which happens a lot, unfortunately). You'll find a much better reference here.

A word boundary is a zero-width assertion: it doesn't consume any characters, it merely asserts that a condition is true. In this case, it asserts that the current position is either followed by a word character and not preceded by one, or preceded by a word character and not followed by one.

If you want to match anything that's not a word character, use \W (note the capital W). But you really only need to match whitespace, which is \s:

"  abc  ".replace(/\s+/, ""); 

If you're trying to do a traditional trim operation, you need to use anchors to make sure you only match whitespace at the very beginning or end of the string:

"  abc  ".replace(/^\s+|\s+$/, ""); 

Upvotes: 3

rogal111
rogal111

Reputation: 5933

\b maches only boundary without spaces, selecting place between space and first/last letter.

use this:

//fulltrim replaces all new lines with space and reduces doubled spaces
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');}

//just trim spaces from begging and ending of string
String.prototype.trim=function(){return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');};

usage

"    ssss   ".fulltrim();
"    
   ssss 
".fulltrim();

Some browsers have implemented trim method.

Upvotes: 0

xiaowl
xiaowl

Reputation: 5217

\b itself does not match character, it matches position. Just like ^ and $.

"\n\t   \n  hello world \t  \n\n".replace(/^\s*/, "").replace(/\s*$/, "");
// return "hello world"

Upvotes: 0

Related Questions