疯狂的技术宅

以前出于工作目的,编写和翻译了大量的技术文章,以前端为主,删掉了过时的、毫无营养的内容,留下的都是精华。


  • 首页

  • 分类

  • 标签

  • 归档

  • 关于本站

  • 回到主站

  • 搜索

JavaScript 中替换字符串的几种方法

时间: 2020-10-16 分类: 前端技术   字数: 414 字 阅读: 1分钟
标签: #JavaScript# #字符串# #替换#
  • 本文译自:https://www.digitalocean.com/community/tutorials/replace-all-instances-of-a-string-in-javascript
  • 译者:疯狂的技术宅

替换字符串中的文本是 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

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

标签: #JavaScript# #字符串# #替换#

标题:JavaScript 中替换字符串的几种方法

链接:https://fe-tech.viewnode.com/post/202010/16/

作者:疯狂的技术宅

声明: 本博客文章除特别声明外,均采用 CC BY-NC-ND 4.0 国际许可协议( 知识共享署名-非商业性使用-禁止演绎 4.0),转载请注明出处!

在 Vue.js 中集成 CSS 框架
用 EventEmitter 处理 Node.js 中的事件
  • 文章目录
  • 站点概览
疯狂的技术宅

疯狂的技术宅

退休程序员,硬件发烧友,人工智能爱好者。写写代码喝喝茶,晒晒太阳带带娃。

457 日志
8 分类
583 标签
GitHub
友情链接
  • viewnode
  • mofish
标签云
  • Javascript 172
  • Node.Js 62
  • Vue 36
  • Typescript 28
  • 实战项目 28
  • 面试 21
  • React 20
  • Css 17
  • 面试题 16
  • 教程 13
  • Promise 12
  • Chrome 9
  • Debug 9
  • 调试 9
  • 资源 9
  • Deno 8
  • Dom 8
  • 杂谈 8
  • 正则表达式 8
  • 测试 8
  • 替换单个字串
  • 替换多个子串
  • 替换特殊字符
© 2018 - 2022 疯狂的技术宅 All Rights Reserved
Powered by - Hugo v0.99.0 / Theme by - NexT
Storage by 俺的服务器 / 冀ICP备2022010157号
0%