Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

regex - Javascript equivalent of Perl's Q ... E or quotemeta()

In Perl regular expressions, you can surround a subexpression with Q and E to indicate that you want that subexpression to be matched as a literal string even if there are metacharacters in there. You also have the quotemeta function that inserts exactly the right number of backslashes in a string so that if you subsequently interpolate that string into a regular expression, it will be matched literally, no matter what its contents were.

Does Javascript (as deployed in major browsers) have any built in equivalent? I can write my own just fine, but I would like to know if I don't have to bother.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no such built-in feature.

Rather than implementing your own, I advise you look into the multitude of regex escape functions available on the internet.

That page proposes the following solution (by Colin Snover):

RegExp.escape = function(text) {
    return text.replace(/[-[]{}()*+?.,\^$|#s]/g, "\$&");
}

or advises to use the XRegExp library.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...