Reputation: 11
I have a problem with regular expression:
var regex = new RegExp('(^|\\s)' + clsName + '(\\s|$)');
What does (^|\\s)
mean? Isn't it equal to (^|\s)
, what does (^|)
mean?
Am I right, it means that the string should start with any letter or white space? I tried to test with browser and console.log but still can't get any solution.
In all tutorials \s
is used to be a space pattern not \\s
.
Ok i got it, the problem was:
When using the RegExp constructor: for each backslash in your regular expression, you have to type \\
in the RegExp constructor. (In JavaScript strings, \\
represents a single backslash!) For example, the following regular expressions match all leading and trailing whitespaces (\s); note that \\s
is passed as part of the first argument of the RegExp constructor:
re = /^\s+|\s+$/g
re = new RegExp('^\\s+|\\s+$','g')
Upvotes: 0
Views: 5151
Reputation: 3446
Why not just split the string on " "?
var string = 'abc defh ij klm';
var elements = string.split(' ');
var clsName = 'abc';
elements.filter(function (el) {
return el === clsName;
});
No need for a RegEx like the one you posted.
Upvotes: 0
Reputation: 138017
(^|\\s)
means: Start of the string (^
) OR (|
) a space \\s
.
If clsName
is "abc"
, for example, it builds the pattern (^|\\s)abc(\\s|$)
. That searches for "abc"
at the start, middle, or end of the string, and it may be surrounded by spaces, so these are valid:
"abc"
"abc x"
"x abc"
"x abc y"
Note that here you are using a string to build a RegExp. JavaScript ignores escape characters it doesn't know - '\s'
would be the same as 's'
, which isn't right.
Another option is to use word boundaries, but might fail on some case (for example, searching for btn
would match for btn-primary
):
var regex = new RegExp('\\b' + clsName + '\\b');
I'd also warn that clsName
might contain regex meta-characters, so you may want to escape it.
Upvotes: 2