如何替换Java字符串中所有出现的字符串? [英] How to replace all occurrences of a string in Javascript?
问题描述
我的Javascript代码中包含以下字符串:
I have this string in my Javascript code:
"Test abc test test abc test test test abc test test abc"
正在做
str = str.replace('abc', '');
似乎只删除了上面字符串中第一次出现的abc
.
seems to only remove the first occurrence of abc
in the string above.
如何替换所有出现的 ?
推荐答案
Update: In the latest versions of most popular browsers, you can use replaceAll
as shown here:
let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"
但是请先检查我可以使用或其他兼容性表来确保您要定位的浏览器首先增加了对它的支持.
But check Can I use or another compatibility table first to make sure the browsers you're targeting have added support for it first.
对于Node以及与旧版/非当前浏览器的兼容性:
For Node and compatibility with older/non-current browsers:
注意:请勿在性能关键代码中使用以下解决方案.
作为正则表达式的一种简单文字字符串的替代方法,您可以使用
As an alternative to regular expressions for a simple literal string, you could use
str = "Test abc test test abc test...".split("abc").join("");
一般模式是
str.split(search).join(replacement)
在某些情况下,它过去比使用replaceAll
和正则表达式要快,但是在现代浏览器中,情况似乎不再如此.
This used to be faster in some cases than using replaceAll
and a regular expression, but that doesn't seem to be the case anymore in modern browsers.
基准: https://jsperf.com/replace-all-vs-split-加入
结论:如果您有性能至关重要的用例(例如,处理数百个字符串),请使用Regexp方法.但是对于大多数典型的用例来说,不必担心特殊字符是很值得的.
Conclusion: If you have a performance critical use case (e.g processing hundreds of strings), use the Regexp method. But for most typical use cases, this is well worth not having to worry about special characters.
这篇关于如何替换Java字符串中所有出现的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!