如何在JavaScript中执行str_replace,替换JavaScript中的文本?
作者:互联网
我想使用str_replace或其类似的替代方法来替换JavaScript中的一些文本.
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write("new_text");
应该给
this is some sample text that i dont want to replace
If you are going to regex, what are the performance implications in
comparison to the built in replacement methods.
解决方法:
使用正则表达式替换字符串比使用字符串替换要慢得多.
如on JSPerf所示,创建正则表达式可以有不同的效率级别,但所有这些都比简单的字符串替换慢得多. The regex is slower because:
Fixed-string matches don’t have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it’s unlikely to beat indexing into a string in the common case.
对于JS perf页面上的简单测试运行,我已经记录了一些结果:
<script>
// Setup
var startString = "xxxxxxxxxabcxxxxxxabcxx";
var endStringRegEx = undefined;
var endStringString = undefined;
var endStringRegExNewStr = undefined;
var endStringRegExNew = undefined;
var endStringStoredRegEx = undefined;
var re = new RegExp("abc", "g");
</script>
<script>
// Tests
endStringRegEx = startString.replace(/abc/g, "def") // Regex
endStringString = startString.replace("abc", "def", "g") // String
endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String
endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp
endStringStoredRegEx = startString.replace(re, "def") // saved regex
</script>
Chrome 68的结果如下:
String replace: 9,936,093 operations/sec
Saved regex: 5,725,506 operations/sec
Regex: 5,529,504 operations/sec
New Regex String: 3,571,180 operations/sec
New Regex: 3,224,919 operations/sec
从这个答案的完整性(借鉴评论)开始,值得一提的是.replace只替换了匹配字符的第一个实例.它只能用// g替换所有实例.如果替换多个实例name.replace(”,’_’),那么表现权衡和代码优雅可能会更糟.替换(”,’_’).replace(”,’_’);或更糟糕的是(name.includes(”)){name = name.replace(”,’_’)}
标签:str-replace,javascript,replace 来源: https://codeday.me/bug/20190925/1817453.html