Matching String Using Variable In Regular Expression With $ And ^
Solution 1:
var strtomatch = "something";
var name = '^something$';
var re = new RegExp(name,"gi");
document.write(strtomatch.match(re));
The i
is for ignoring case.
This matches just word "something" and will not match somethingelse.
if you are looking to match it in the middle of a sentence, you should use the following in your code
var name = ' something ';
Alernately, using word boundaries,
var name = '\\bsomething\\b';
Solution 2:
If you're saying you want to match something
at the beginning or end of the string then do this:
/^something|something$/
With your variable:
new RegExp("^" + name + "|" + name + "$");
EDIT: For your updated question, you want the name
variable to be the entire string matched, so:
new RegExp("^" + name + "$"); // note: the "g" flag from your question
// is not needed if matching the whole string
But that is pointless unless name
contains a regular expression itself because although you could say:
var strToTest = "something",
name = "something",
re = new RegExp("^" + name + "$");
if (re.test(strToTest)) {
// do something
}
You could also just say:
if (strToTest === name) {
// do something
}
EDIT 2: OK, from your comment you seem to be saying that the regex should match where "something" appears anywhere in your test string as a discrete word, so:
"something else" // should match
"somethingelse" // should not match
"This is something else" // should match
"This is notsomethingelse" // should not match
"This is something" // should match
"This is something." // should match?
If that is correct then:
re = new RegExp("\\b" + name + "\\b");
Solution 3:
You should use /\bsomething\b/
. \b
is to match the word boundary.
"A sentence using something".match(/\bsomething\b/g);
Post a Comment for "Matching String Using Variable In Regular Expression With $ And ^"