简体   繁体   中英

Auto escape Regex in JavaScript?

How to create an escaped regular expression out of any possible regex string? There are already many answers to this question, for example:

function escapeRegex(string) {
    return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var text = 'test123',
    reString = '\d+',
    escaped = escapeRegex(reString),
    re = new RegExp(escaped);
console.log(re);                //returns /d\+/
console.log(text.match(re));    //returns null

But this function does not return all the numbers from the text, which was expected in this example.

If I've understood your question correctly, you don't need the escape function at all. Instead, you could use Tagged Template . Something like this:

 function escapeRegex(string) { return string.raw[0]; } var text = 'test123', escaped = escapeRegex `\d+`, re = new RegExp(escaped); console.log(re); console.log(text.match(re));

In the case the string doesn't need any further modifications, you can also use String.raw method instead of a tagged function, like so:

escaped = String.raw`\d+`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM