问题
My string contains some of the special characters that needs to be escaped with (\) double backslash before the string. My piece of code below:
var data = "abckdef)ghijkl)-8-mno-3-(pqrstuvw-1-xyz)-5-thiaa-1-aza-";
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?~_";
for (var i = 0; i < data.length; i++) {
if (iChars.indexOf(data.charAt(i)) != -1) {
console.log("Your string has special characters. \nThese are not allowed.");
return false;
}
}
Expected Result would be:
abckdef\)ghijkl\)\-8\-mno\-3\-\(pqrstuvw\-1\-xyz\)\-5\-thiaa\-1\-aza\-
Above code finds the special characters in my string, but I wanted to add (\\) before every occurrences of the special characters. Any help on this?
回答1:
Use a regex replacement:
Match:
/[!@#$%^&*()+=\-[\]\\';,./{}|":<>?~_]/
Replace to:
\$&
>>> data.replace(/[!@#$%^&*()+=\-[\]\\';,./{}|":<>?~_]/g, "\\$&")
... "abckdef\)ghijkl\)\-8\-mno\-3\-\(pqrstuvw\-1\-xyz\)\-5\-thiaa\-1\-aza\-"
回答2:
Regex:
([!@#$%^&*()+=\[\]\\';,./{}|":<>?~_-])
Replacement string:
\$1
DEMO
> var data = "abckdef)ghijkl)-8-mno-3-(pqrstuvw-1-xyz)-5-thiaa-1-aza-";
undefined
> var result = data.replace(/([!@#$%^&*()+=\[\]\\';,./{}|":<>?~_-])/g, "\\$1");
undefined
> console.log(result);
abckdef\)ghijkl\)\-8\-mno\-3\-\(pqrstuvw\-1\-xyz\)\-5\-thiaa\-1\-aza\-
回答3:
Try this plug and play function.
var data = "abckdef)ghijkl)-8-mno-3-(pqrstuvw-1-xyz)-5-thiaa-1-aza-";
function escapeSpecialCaseChar(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
console.log(escapeSpecialCaseChar(data));
回答4:
Do you want to escape anything other than alphanumeric character then make it simple
Find what :([^a-zA-Z0-9])
Replacement: \\$1
regex101 demo
Sample code:
var re = /([^a-zA-Z0-9])/g;
var str = 'abckdef)ghijkl)-8-mno-3-(pqrstuvw-1-xyz)-5-thiaa-1-aza-';
var subst = '\\$1';
var result = str.replace(re, subst);
output: (same as expected)
abckdef\)ghijkl\)\-8\-mno\-3\-\(pqrstuvw\-1\-xyz\)\-5\-thiaa\-1\-aza\-
来源:https://stackoverflow.com/questions/25376698/javascript-code-to-check-special-characters-and-add-double-slash-before-that