替换字符串中的文本是 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 能够替换所有子串js中怎么替换字符串,必须通过 /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 之外js中怎么替换字符串,还可以使用 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

  在第二个例子中不必用反斜杠来转义反斜杠。

  你还知道哪些方法,请留言告诉大家。

  本文研究几种用replace和正则表达式替换文本的方法

TAGS:转义 正则表达式 js替换字符串中的字符 js 字段串替换 replace js中怎么替换字符串 replace函数
!如链接失效请在下方留言。本站所有资源均来源于网络,版权属于原作者!仅供学习参考,本站不对您的使用负任何责任。如果有侵权之处请第一时间联系我们删除,敬请谅解!