Here is the code to escape special characters:
function escapeRegExp(string){
return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
}
How can I unescape the special characters to get the original strings?
I am getting confused with use of / and //.
That's pretty easy, you can use another function that removes the \\
characters.
// Use this to escape
function escapeRegExp(string){
return string.replace(/([\.\*\+\?\^\$\{\}\(\)\|\[\]\/\\])/g, "\\$1");
}
// And this to unescape
function unescapeRegExp(string) {
return string.replace(/\\([\.\*\+\?\^\$\{\}\(\)\|\[\]\/\\])/g, "$1")
}
// EXAMPLE:
escapeRegExp(".?[]");
> "\.\?\[\]"
unescapeRegExp("\.\?\[\]");
> ".?[]"
PS: I corrected your original function, the regular expression was wrong.
I guess, you've take this from MDN .
All you need to revert escaping is to remove every odd occurence of \\
character.
function unescapeRegExp(string) {
return string.replace(/\\(.)/g, '$1');
}
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.