开发者

Escape regexp strings? [duplicate]

开发者 https://www.devze.com 2023-03-23 02:59 出处:网络
This question already has answers here: 开发者_StackOverflow社区 Is there a RegExp.escape function in JavaScript?
This question already has answers here: 开发者_StackOverflow社区 Is there a RegExp.escape function in JavaScript? (18 answers) Closed 4 years ago.

I recall there was a way to have a very long string Regex escaped.

I think I used new Regexp but I can't recall how to do it.

Anyone here who knows how?


Your question is a little unclear. But if I understand you well, you need a way to escape the string in order to use it later in regular expressions.

PHP has a function preg_quote for this purpose. And there is a port of this function to JavaScript:

function preg_quote (str, delimiter) {
    // Quote regular expression characters plus an optional character  
    // 
    // version: 1107.2516
    // discuss at: http://phpjs.org/functions/preg_quote
    // +   original by: booeyOH
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: preg_quote("$40");
    // *     returns 1: '\$40'
    // *     example 2: preg_quote("*RRRING* Hello?");
    // *     returns 2: '\*RRRING\* Hello\?'
    // *     example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
    // *     returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'
    return (str + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
}

Original source: http://phpjs.org/functions/preg_quote:491

Example of usage:

var strToMatch = "{test}??)(**test";
var subject = "Hello{test}??)(**testWorld";
var re = new RegExp( preg_quote(strToMatch) );

if ( subject.match(re) ) 
    document.write('TRUE');
else 
    document.write('FALSE');

Output:

TRUE

A working example: http://jsfiddle.net/37maV/


Short 'n Sweet (and Complete)

function escapeRegExp(str) {
  return str.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

var re = new RegExp(escapeRegExp(str));   

See: Escape string for use in Javascript regex


Suggest you turn it into a string and then convert to a regex object using new RegExp(, as shown below:

var rxstr = "[\d]" + 
            "[\w]";
var rx = new RegExp(rxstr);

Or you could try (at the expense of formatting):

var x = "test";
var rxstr = "[\d]\
[\w]";
var rx = new RegExp(rxstr);
alert(rx);

The latter is faster as it does not create a number of new strings, but could be agued to be less readable.

0

精彩评论

暂无评论...
验证码 换一张
取 消