如何替换 JavaScript 中所有出现的字符串 [英] How to replace all occurrences of a string in JavaScript

查看:41
本文介绍了如何替换 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.

如何替换所有出现的它?

推荐答案

更新: 在最流行的浏览器的最新版本中,您可以使用 replaceAll如图所示:

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://jsben.ch/TZYzj

结论:如果您有一个性能关键的用例(例如处理数百个字符串),请使用 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.

这篇关于如何替换 JavaScript 中所有出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆