regex - javascript code to check special characters and add double slash before that? -
my string contains of special characters needs escaped (\) double backslash before string. piece of code below:
var data = "abckdef)ghijkl)-8-mno-3-(pqrstuvw-1-xyz)-5-thiaa-1-aza-"; var ichars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?~_"; (var = 0; < data.length; i++) { if (ichars.indexof(data.charat(i)) != -1) { console.log("your string has special characters. \nthese not allowed."); return false; } } expected result be:
abckdef\)ghijkl\)\-8\-mno\-3\-\(pqrstuvw\-1\-xyz\)\-5\-thiaa\-1\-aza\- above code finds special characters in string, wanted add (\\) before every occurrences of special characters. on this?
use regex replacement:
match:
/[!@#$%^&*()+=\-[\]\\';,./{}|":<>?~_]/ replace to:
\$& >>> data.replace(/[!@#$%^&*()+=\-[\]\\';,./{}|":<>?~_]/g, "\\$&") ... "abckdef\)ghijkl\)\-8\-mno\-3\-\(pqrstuvw\-1\-xyz\)\-5\-thiaa\-1\-aza\-"
Comments
Post a Comment