Jake
Jake

Reputation: 1332

RegEx match with special characters

I have a string.match condition that was working until I realized that some words are "personal(computer)" have special characters like parentheses in the word. For example my code is grabbing the term to compare to which would be "personal(computer)" and searching through data to find any instance of that, but by using

string1.match(stringtarget,"ig"); //returns null 

I am a novice with regex, so how could I fix this to work for special characters as well.

Upvotes: 1

Views: 4597

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318488

You can use the preg_quote javascript port to escape regex-specific characters.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074058

If you don't need the regular expression features, you can use indexOf:

if (string1.toLowerCase().indexOf(stringtarget.toLowerCase()) >= 0) {
    // It's in there
}

Otherwise (and I'm guessing you're using match for a reason!), you'll have to pre-process the stringtarget to escape any special characters.

For instance, this is a function I used in a recent project to do exactly that, which is inspired by a similar PHP function:

if (!RegExp.escape) {
    (function() {
        // This is drawn from http://phpjs.org/functions/preg_quote:491
        RegExp.escape = RegExp_escape;
        function RegExp_escape(str) {
            return String(str).replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, '\\$1');
        }
    })();
}

And so:

var match = string1.match(RegExp.escape(stringtarget),"ig");

Upvotes: 3

Related Questions