简体   繁体   中英

JavaScript String Replace all

I have the following string and I want to replace all special characters of a string.

let data = "`test@#$demo%^here[sf.s]\|demo{delata}*testing?+$^()`"

Special characters:

let spcial=[".", "+", "*", "?", "^", "$", "(", ")", "[", "]", "{", "}", "|", "\"];

final output:

test@#\\$demo%\\^here\\[sf\\.s\\]\\\\\|demo\\{delata\\}\\*testing\\?\\+\\$\\^\\(\\)

In short, I want to add \ in front of a special character so How I can do it?

 let data = "`test@#$demo%^here[sf.s]\\|demo{delata}*testing?+$^()`" let spcial=[".", "+", "*", "?", "^", "$", "(", ")", "[", "]", "{", "}", "|", "\\"] const res = data.split("").map(ch => spcial.includes(ch)? "\\\\" + ch: ch).join("") console.log(res)

 let data = "`test@#$demo%^here[sf.s]\|demo{delata}*testing?+$^()`" let spcial=[".", "+", "*", "?", "^", "$", "(", ")", "[", "]", "{", "}", "|", "\\"] for (let c of data) { if(spcial.includes(c) ) { data = data.replace(c, '\\'+c) } } console.log(data)

 str = "test@#$demo%^here[sf.s]\|demo{delata}*testing?+$^()"; const spcial=[".", "+", "*", "?", "^", "$", "(", ")", "[", "]", "{", "}", "|", "\\"]; spcial.forEach(myFunction); function myFunction(value) { str = str.replaceAll(value, "\\" + value); } console.log(str)

I think it'll do you good in the long run to learn some Regular Expressions (regex/regexp). A regular expression that I've used to find special characters is /[^a-zA-Z0-9]/g . If you use the replace method with a callback function, you can take the matched special character m and be able to replace it with \\${m} .

Read more about RegEx here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Read more about replace here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

To do exactly what you want to have above, this would be a regex implementation:

const data = "`test@#$demo%^here[sf.s]|demo{delata}*testing?+$^()`";
const specialCharacters = /\.|\+|\*|\?|\^|\$|\(|\)|\[|\]|\{|\}|\||\\/g;
const output = data.replace(specialCharacters, (m) => `\\${m}`);

console.log(output);

I recommend checking for more special characters.

const data = "`test@#$demo%^here[sf.s]|demo{delata}*testing?+$^()`";
const output = data.replace(/[^a-zA-Z0-9]/g, (m) => `\\${m}`);
console.log(output);
let data = "`test@#$demo%^here[sf.s]\|demo{delata}*testing?+$^()`";
let special=[".", "+", "*", "?", "^", "$", "(", ")", "[", "]", "{", "}", "|", "\\"];
let [...chars] = data;
chars = chars.map(char => {
    if (special.includes(char)) return `\\${char}`;
    return char;
}
data = chars.join("");

Approach 1: From a fixed list of special chars

You can replace it all at once, with a regular expression like this:

 let data = "test@#$demo%^here[sf.s]\|demo{delata}*testing?+$^()"; let replaced = data.replace(/[\.\+\*\?\^\$\(\)\[\]\{\}\|\\]/g, '\\$&'); console.log(replaced);

Note that the special chars are listed, escaped with a backslash, inside the regular expression. If you want to learn more about how this works, take a look here, in the "Explain" section .

Approach 2: From a dynamic list of special chars

If you want to build this regular expression dynamically from an array, you can do it like this:

 let data = "test@#$demo%^here[sf.s]\|demo{delata}*testing?+$^()"; let specialChars = [".", "+", "*", "?", "^", "$", "(", ")", "[", "]", "{", "}", "|", "\\"]; let regexp = new RegExp(`[\\${specialChars.join('\\')}]`, 'g'); let replaced = data.replace(regexp, '\\$&'); console.log(replaced);

Result

in both examples the result will be:

test@#\$demo%\^here\[sf\.s\]\|demo\{delata\}\*testing\?\+\$\^\(\)

Using a global replace (denoted by g at the end), you can replace all characters at once, without need for loops.

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