简体   繁体   中英

Javascript regex to add to every character of a string a backslash

So as the title says I'd like to add to every character of a string a backslash, whether the string has special characters or not. The string should not be considered 'safe'

eg: 
let str = 'dj%^3&something';
str = str.replace(x, y);
// str = '\d\j\%\^\3\&\s\o\m\e\t\h\i\n\g'

You could capture every character in the string with (.) and use \\\\$1 as replacement, I'm not an expert but basically \\\\ will render to \\ and $1 will render to whatever (.) captures.

HIH

EDIT

please refer to Wiktor Stribiżew's comment for an alternative which will require less coding. Changes as follows:

str = str.replace(/(.)/g, '\\\\$1'); for str = str.replace(/./g, '\\\\$&');

Also, for future reference I strongly advice you to visit regexr.com when it comes to regular expressions, it's helped ME a lot

 let str = 'dj%^3&something'; str = str.replace(/(.)/g, '\\\\$1'); console.log(str); 

If you just want to display a string safely, you should just do:

let str = 'dj%^3&something';
let node = document.createTextNode(str);
let dest = document.querySelector('.whatever');
dest.appendChild(node);

And then you are guaranteed that it will be treated as text, and won't be able to execute a script or anything.

For example: https://jsfiddle.net/s6udj03L/1/

You can split the string to an array, add a \\ to each element to the array, then joint the array back to the string that you wanted.

 var str = 'dj%^3&something'; var split = str.split(""); // split string into array for (var i = 0; i < split.length; i++) { split[i] = '\\\\' + split[i]; // add backslash to each element in array } var joint = split.join('') // joint array to string console.log(joint); 

If you don't care about creating a new string and don't really have to use a regex, why not just iterate over the existing one and place a \\ before each char . Notice to you have to put \\\\ to escape the first \\ .

To consider it safe, you have to encode it somehow. You could replace typical 'non-safe' characters like in the encode() function below. Notice how & get's replaced by &amp;

 let str = 'dj%^3&something'; let out = ""; for(var i = 0; i < str.length; i++) { out += ("\\\\" + str[i]); } console.log(out); console.log(encode(out)); function encode(string) { return String(string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM