js字符串替换

js字符串替换

1.替换单个字符串

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 字串。

2.替换多个字符串
如果希望 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"

3.替换特殊字符串
要替换特殊字符,例如 -/\^$*+?.()|[]{}),需要使用反斜杠对其转义。
如果给定字符串 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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端鼓励师

老铁 支持一波

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值