JavaScript 中替换字符串的几种方法
替换字符串中的中替文本是 JavaScript 开发中的常见任务。本文研究几种用 replace 和正则表达式替换文本的换字方法。
替换单个字串通常 JavaScript 的符串方法 String replace() 函数只会替换它在字符串中找到的第一个匹配的高防服务器子符:
const myMessage = this is the sentence to end all sentences; const newMessage = myMessage.replace(sentence, message); console.log(newMessage); // this is the message to end all sentences在这个例子中,仅替换了第一个 sentence 字串。中替
替换多个子串
如果希望 JavaScript 能够替换所有子串,换字必须通过 /g 运算符使用正则表达式:
const myMessage = this is the sentence to end all sentences; const newMessage = myMessage.replace(/sentence/g,符串方法 message); console.log(newMessage); // this is the message to end all messages这一次次两个子串都会被替换。
除了使用内联 /g 之外,中替还可以使用 RegExp 对象的换字构造函数:
const myMessage = this is the sentence to end all sentences; const newMessage = myMessage.replace(new RegExp(sentence, g), message); console.log(newMessage); // this is the message to end all messages```替换特殊字符
要替换特殊字符,例如 -/\^$*+?符串方法.()|[]{ }),云服务器提供商需要使用反斜杠对其转义。中替
如果给定字符串 this\-is\-my\-url,换字要求把所有转义的符串方法减号( \-)替换为未转义的减号(-)。
可以用 replace() 做到:
const myUrl = this\-is\-my\-url; const newUrl = myMessage.replace(/\\-/g,中替 -); console.log(newUrl); // this-is-my-url或者用new Regexp():
const myUrl = this\-is\-my\-url; const newUrl = myUrl.replace(new RegExp(\-, g), -); console.log(newUrl); // this-is-my-url在第二个例子中不必用反斜杠来转义反斜杠。
换字