darren <> writes:
> We have some code that makes a RegExp object out of a variable:
>
> var xxx = new RegExp(aString);
>
> The problem is that sometimes the string contains regular expression
> characters so the match isn't happening as we would like. For example
> I want to match the literal string "[1-1]" but when this is the
> variable that is made into a RegExp, I think it is interpreted as a
> range because of the [] characters. Is there anyway I can tell the
> constructor that I want to match [1-1]? I basically want to escape
> any special characters: \[1-1\]
The short answer is that if you need to look for a exact match,
you don't need regexps.
Just check
if (someString.indexOf(aString) >= 0) ...
If the reason you want to create a regexp to match a literal string is
that you have some generic function that takes a regexp as argument in
order to test against strings (this happens quite often), then you should
increase the abstraction level and change the function to accept a test
function instead of a regexp.
And finally, if you can't change anything, you can escape all
meaningfull characters of the string:
function escapeRegExp(literal) {
return literal.replaceAll(/([[(){.*+?\\$^|])/g,"\\$1");
}
/L
--
Lasse Reichstein Nielsen -
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'