Skip to content Skip to sidebar Skip to footer

Matching String Using Variable In Regular Expression With $ And ^

This is probably a very easy question to answer, but I haven't figure out what is the correct way to do it. I need to match a text via regular expressions using ^ and $ to only mat

Solution 1:

var strtomatch = "something";
var name = '^something$';
var re = newRegExp(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';

Working Example

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:

newRegExp("^" + name + "|" + name + "$");

EDIT: For your updated question, you want the name variable to be the entire string matched, so:

newRegExp("^" + 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 = newRegExp("^" + 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 ^"