介绍
代替字符串中的文本是JavaScript中常见的任务. 在本文中,您将研究使用代替
和常规表达式来代替文本。
<$>[注] 注: 参阅此伴侣教程以详细概述如何在Linux中使用‘grep’和常规表达式来搜索文本模式。
前提条件
- 熟悉 JavaScript 编程语言. 访问我们的教程系列, 如何在 JavaScript 中编码,以了解基本知识
取代一个单一机构
通常,JavaScript的代替字符串()
函数只取代它在字符串中找到的第一个实例:
1[label app.js]
2const myMessage = 'this is the sentence to end all sentences';
3const newMessage = myMessage.replace('sentence', 'message');
4console.log(newMessage); // this is the message to end all sentences
在本例中,仅取代了判决
的第一例。
取代多个机构
如果您希望 JavaScript 取代所有实例,则需要使用使用 /g
运算符的常规表达式:
1[label app.js]
2const myMessage = 'this is the sentence to end all sentences';
3const newMessage = myMessage.replace(/sentence/g, 'message');
4console.log(newMessage); // this is the message to end all messages
这一次,双方都被改变了。
除了使用内线 /g
外,您还可以使用对象 RegExp
的构建函数:
1[label app.js]
2const myMessage = 'this is the sentence to end all sentences';
3const newMessage = myMessage.replace(new RegExp('sentence', 'g'), 'message');
4console.log(newMessage); // this is the message to end all messages
取代特殊人物
要取代特殊字符,如 -/\^$*+?()̧[]{})
,我们将需要使用背影来逃避它们。
鉴于字符串 this\-is\-my\-url
,让我们用未逃避的字符串(-
)代替所有逃避的字符串(-
)。
您可以使用`代替():
1[label app.js]
2const myUrl = 'this\-is\-my\-url';
3const newUrl = myMessage.replace(/\\-/g, '-');
4console.log(newUrl); // this-is-my-url
或者使用「新 Regexp()」:
1[label app.js]
2const myUrl = 'this\-is\-my\-url';
3const newUrl = myUrl.replace(new RegExp('\-', 'g'), '-');
4console.log(newUrl); // this-is-my-url
在这个第二个例子中,您不需要使用背影来逃避背影。
结论
在本文中,您看到如何更换单个实例、多个实例以及如何用特殊字符处理字符串。