替换字符串中所有字符实例的最快方法 [英] Fastest method to replace all instances of a character in a string

查看:116
本文介绍了替换字符串中所有字符实例的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中替换字符串中所有字符串/字符实例的最快方法是什么? -loop,正则表达式?

What is the fastest way to replace all instances of a string/character in a string in JavaScript? A while, a for-loop, a regular expression?

推荐答案

最简单的方法是使用带有 g 标志的正则表达式替换所有实例:

The easiest would be to use a regular expression with g flag to replace all instances:

str.replace(/foo/g, "bar")

这将在字符串<$ c中用 bar 替换所有出现的 foo $ C> STR 。如果您只有一个字符串,可以将其转换为RegExp对象,如下所示:

This will replace all occurrences of foo with bar in the string str. If you just have a string, you can convert it to a RegExp object like this:

var pattern = "foobar",
    re = new RegExp(pattern, "g");

这篇关于替换字符串中所有字符实例的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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