我的JavaScript代码中有以下字符串:
"Test abc test test abc test test test abc test test abc"
做:
str = str.replace('abc', '');
似乎只删除了上面字符串中第一个出现的abc
.
我如何替换它的all个实例?
我的JavaScript代码中有以下字符串:
"Test abc test test abc test test test abc test test abc"
做:
str = str.replace('abc', '');
似乎只删除了上面字符串中第一个出现的abc
.
我如何替换它的all个实例?
Update:在最新版本的最流行浏览器中,您可以使用replaceAll
如下所示:
let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"
但是,首先判断Can I use或其他兼容性表,以确保您针对的浏览器首先添加了对它的支持.
有关 node 和与旧浏览器/非当前浏览器的兼容性:
Note: Don't use the following solution in performance critical code.个
作为简单文字字符串正则表达式的替代方法,可以使用
str = "Test abc test test abc test...".split("abc").join("");
一般的模式是
str.split(search).join(replacement)
在某些情况下,这比使用replaceAll
和正则表达式更快,但在现代浏览器中似乎不再如此.
如果您有一个性能关键的用例(例如处理数百个字符串),请使用Regexp方法.但是对于大多数典型的用例来说,不必担心特殊字符是值得的.