JavaScript 中替换字符串的几种方法
文章目录
作者:Chris On Code翻译:疯狂的技术宅
原文:https://www.digitalocean.com/...
未经允许严禁转载
替换字符串中的文本是 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在第二个例子中不必用反斜杠来转义反斜杠。
你还知道哪些方法,请留言告诉大家。

本文首发微信公众号:前端先锋
欢迎扫描二维码关注公众号,每天都给你推送新鲜的前端技术文章
欢迎继续阅读本专栏其它高赞文章:
- 深入理解Shadow DOM v1
- 一步步教你用 WebVR 实现虚拟现实游戏
- 13个帮你提高开发效率的现代CSS框架
- 快速上手BootstrapVue
- JavaScript引擎是如何工作的?从调用栈到Promise你需要知道的一切
- WebSocket实战:在 Node 和 React 之间进行实时通信
- 关于 Git 的 20 个面试题
- 深入解析 Node.js 的 console.log
- Node.js 究竟是什么?
- 30分钟用Node.js构建一个API服务器
- Javascript的对象拷贝
- 程序员30岁前月薪达不到30K,该何去何从
- 14个最好的 JavaScript 数据可视化库
- 8 个给前端的顶级 VS Code 扩展插件
- Node.js 多线程完全指南
- 把HTML转成PDF的4个方案及实现

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论