简体   繁体   English

JavaScript 字符串全部替换

[英]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:最后 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).我认为从长远来看,学习一些正则表达式 (regex/regexp) 对您有好处。 A regular expression that I've used to find special characters is /[^a-zA-Z0-9]/g .我用来查找特殊字符的正则表达式是/[^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} .如果您将replace方法与回调 function 一起使用,您可以获取匹配的特殊字符m并能够将其替换为\\${m}

Read more about RegEx here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp在此处阅读有关 RegEx 的更多信息: 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在此处阅读有关replace的更多信息: 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方法 1:来自固定的特殊字符列表

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方法 2:来自特殊字符的动态列表

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.使用全局替换(最后用g表示),您可以一次替换所有字符,而无需循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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