首頁 > web前端 > js教程 > 主體

JavaScript如何替換字串? 3種方法介紹

青灯夜游
發布: 2020-11-02 17:49:06
轉載
19445 人瀏覽過

JavaScript如何替換字串? 3種方法介紹

替换字符串中的文本是 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
登入後複製

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

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

相关免费学习推荐:js视频教程

更多编程相关知识,请访问:编程入门!!

以上是JavaScript如何替換字串? 3種方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:segmentfault.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!