在JavaScript中替换字符串/字符的所有实例的最快方法是什么?while, for循环,正则表达式?
当前回答
@Gumbo添加额外的答案- user.email.replace(/foo/gi,"bar");
/foo/g - Refers to the all string to replace matching the case sensitive
/foo/gi - Refers to the without case sensitive and replace all For Eg: (Foo, foo, FoO, fOO)
DEMO
其他回答
使用String对象的replace()方法。
正如所选答案中提到的,应该在正则表达式中使用/g标志,以便替换字符串中子字符串的所有实例。
var mystring = 'This is a string';
var newString = mystring.replace(/i/g, "a");
newString现在是'Thas as a strange '
仅从速度问题考虑,我相信上面链接中提供的区分大小写的示例将是目前为止最快的解决方案。
var token = "\r\n";
var newToken = " ";
var oldStr = "This is a test\r\nof the emergency broadcasting\r\nsystem.";
newStr = oldStr.split(token).join(newToken);
newStr是 “这是对紧急广播系统的一次测试。”
你可以使用以下方法:
newStr = str.replace(/[^a-z0-9]/gi, '_');
or
newStr = str.replace(/[^a-zA-Z0-9]/g, '_');
这将替换所有不是字母或数字的字符('_')。简单地更改下划线值的任何你想替换它。
I tried a number of these suggestions after realizing that an implementation I had written of this probably close to 10 years ago actually didn't work completely (nasty production bug in an long-forgotten system, isn't that always the way?!)... what I noticed is that the ones I tried (I didn't try them all) had the same problem as mine, that is, they wouldn't replace EVERY occurrence, only the first, at least for my test case of getting "test....txt" down to "test.txt" by replacing ".." with "."... maybe I missed so regex situation? But I digress...
因此,我重写了我的实现如下。这是非常简单的,虽然我怀疑不是最快的,但我也不认为现代JS引擎的区别是重要的,除非你在一个紧密的循环中做这件事,但这总是任何事情的情况…
function replaceSubstring(inSource, inToReplace, inReplaceWith) {
var outString = inSource;
while (true) {
var idx = outString.indexOf(inToReplace);
if (idx == -1) {
break;
}
outString = outString.substring(0, idx) + inReplaceWith +
outString.substring(idx + inToReplace.length);
}
return outString;
}
希望这能帮助到别人!
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何删除表中特定列的第一个字符?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我如何等待一个承诺完成之前返回一个函数的变量?