Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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");

Solution 2:

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


Post a Comment for "RegEx Match With Special Characters"