On 2013-04-27 19:56, Joey@still_Learning.invalid wrote:
> I know next to nothing about regex, but I need to determine whether an
> exact match of a string within a string exists. My current code, which
> doesn't work is:
>
> firstString = 'testing';
> testString = 'This is useful for testing cookies';
>
> testTheStrings = testString.search(/\bfirstString\b/);
In addition to what JJ wrote: if you're looking for an exact match and
don't really need the word boundary matches, you could also use indexOf():
var found = testString.indexOf("testing") > -1;
indexOf() can be a lot faster than a regular expression, depending on
the implementation. This example would also match "protesting" and
"testings". You can avoid that by searching for " testing ", if you know
that the word will be surrounded by spaces.
If you do need the regex, but are only interested in a true/false result
of the match, use the test() method instead of search():
var found = /\btesting\b/.test(testString);
It returns a boolean and is faster and arguably more expressive than
search().
If you want to match text stored in a variable, you will need to use the
RegExp() constructor:
var needle = "testing";
var haystack = "This is useful for testing cookies";
var regex = new RegExp("\\b" + needle + "\\b");
var found = regex.test(haystack);
In the third line, needle will be interpreted as part of a regular
expression, so you'll have to make sure that it doesn't contain any
characters that have a special meaning in regular expressions. Or you
can escape them using something like this:
function escapeRegex (str) {
return str.replace(/[\\^$+*?.(){}[\]]|-/g, "\\$&");
}
And once again, I wonder why the RegExp object doesn't have a built-in
method to do this...
One other thing: please don't reuse old threads for new questions. If
you have a new question, start a new thread.
- stefan