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

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -