精彩文章研究几种用replace和正则表达式替换文本的方法,你还知道哪些?

  js中怎么替换字符串_js 字段串替换_js替换字符串中所有相同的字符

  替换字符串中的文本是 JavaScript 开发中的常见任务。本文研究几种用 replace正则表达式替换文本的方法。

  替换单个字串

  通常 JavaScript 的 String replace() 函数只会替换它在字符串中找到的第一个匹配的子符:

  <pre data-tool="mdnice编辑器" style="margin-top: 10px;margin-bottom: 10px;border-radius: 5px;box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;">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 </pre>

  在这个例子中,仅替换了第一个 sentence 字串。

  替换多个子串

  如果希望 JavaScript 能够替换所有子串,必须通过 /g 运算符使用正则表达式:

  <pre data-tool="mdnice编辑器" style="margin-top: 10px;margin-bottom: 10px;border-radius: 5px;box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;">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 </pre>

  这一次次两个子串都会被替换。

  js中怎么替换字符串_js替换字符串中所有相同的字符_js 字段串替换

  除了使用内联 /g 之外js中怎么替换字符串,还可以使用 RegExp 对象的构造函数:

  <pre data-tool="mdnice编辑器" style="margin-top: 10px;margin-bottom: 10px;border-radius: 5px;box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;">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` </pre>

  替换特殊字符

  要替换特殊字符,例如 -/^$*+?.()|[]{}),需要使用反斜杠对其转义

  如果给定字符串 this-is-my-urljs中怎么替换字符串,要求把所有转义的减号( -)替换为未转义的减号(-)。

  可以用 replace() 做到:

  <pre data-tool="mdnice编辑器" style="margin-top: 10px;margin-bottom: 10px;border-radius: 5px;box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;">const myUrl = 'this\-is\-my\-url'; const newUrl = myMessage.replace(/\\-/g, '-'); console.log(newUrl); // this-is-my-url </pre>

  或者用new Regexp():

  <pre data-tool="mdnice编辑器" style="margin-top: 10px;margin-bottom: 10px;border-radius: 5px;box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;">const myUrl = 'this\-is\-my\-url'; const newUrl = myUrl.replace(new RegExp('\-', 'g'), '-'); console.log(newUrl); // this-is-my-url </pre>

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

  你还知道哪些方法,请留言告诉大家。

  js 字段串替换_js替换字符串中所有相同的字符_js中怎么替换字符串

  js 字段串替换_js中怎么替换字符串_js替换字符串中所有相同的字符

  精彩文章回顾,点击直达

  js 字段串替换_js替换字符串中所有相同的字符_js中怎么替换字符串

  js替换字符串中所有相同的字符_js中怎么替换字符串_js 字段串替换

  转一转

  js替换字符串中所有相同的字符_js 字段串替换_js中怎么替换字符串

  赞一赞

  js 字段串替换_js替换字符串中所有相同的字符_js中怎么替换字符串

  看一看

  本文分享自微信公众号 - 前端先锋(jingchengyideng)。

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1603
0 评论
303

发表评论

!