温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript中替换字符串的方法有哪些

发布时间:2020-11-04 10:04:15 来源:亿速云 阅读:149 作者:小新 栏目:web开发

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

替换单个字串

通常 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中替换字符串的方法有哪些就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI