介绍 (Introduction)
Replacing text in strings is a common task in JavaScript. In this article you’ll look at using replace
and regular expressions to replace text.
替换字符串中的文本是JavaScript中的常见任务。 在本文中,您将研究如何使用replace
和正则表达式来替换文本。
更换单个实例 (Replacing A Single Instance)
Normally JavaScript’s String replace()
function only replaces the first instance it finds in a string:
通常,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
In this example, only the first instance of sentence
was replaced.
在此示例中,仅替换了sentence
的第一个实例。
替换多个实例 (Replacing Multiple Instances)
If you want JavaScript to replace all instances, you’ll have to use a regular expression using the /g
operator:
如果您希望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
This time both instances are changed.
这次两个实例都被更改。
In addition to using the inline /g
, you can use the constructor function of the RegExp
object:
除了使用内联/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```
替换特殊字符 (Replacing Special Characters)
To replace special characters like -/\^$*+?.()|[]{})
we’ll need to use a backslash to escape them.
要替换特殊字符,例如-/\^$*+?.()|[]{})
我们需要使用反斜杠将其转义。
Here’s an example. Given the string this\-is\-my\-url
, let’s replace all the escaped dashes (\-
) with an unescaped dash (-
).
这是一个例子。 给定字符串this\-is\-my\-url
,我们将所有转义的破折号( \-
)替换为未转义的破折号( -
)。
You can do this with replace()
:
您可以使用replace()
做到这一点:
const myUrl = 'this\-is\-my\-url';
const newUrl = myMessage.replace(/\\-/g, '-');
console.log(newUrl); // this-is-my-url
Alternatively, use new Regexp()
:
或者,使用new Regexp()
:
const myUrl = 'this\-is\-my\-url';
const newUrl = myUrl.replace(new RegExp('\-', 'g'), '-');
console.log(newUrl); // this-is-my-url
In this second example, you don’t have to use a backslash to escape the backslash.
在第二个示例中,您不必使用反斜杠来转义反斜杠。
结论 (Conclusion)
In this article you saw how to replace single instances, multiple instances, and how to handle strings with special characters.
在本文中,您了解了如何替换单个实例,多个实例以及如何使用特殊字符处理字符串。
翻译自: https://www.digitalocean.com/community/tutorials/replace-all-instances-of-a-string-in-javascript