JavaScript中替换字符串的方法有哪些-创新互联

这篇文章给大家分享的是有关JavaScript中替换字符串的方法有哪些的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

创新互联公司主营伊通网站建设的网络公司,主营网站建设方案,成都app软件开发公司,伊通h5微信小程序开发搭建,伊通网站营销推广欢迎伊通等地区企业咨询

替换单个字串

通常 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

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

感谢各位的阅读!关于JavaScript中替换字符串的方法有哪些就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!


分享文章:JavaScript中替换字符串的方法有哪些-创新互联
URL分享:http://myzitong.com/article/hojdi.html