如何在 JavaScript 中执行 str_replace,替换 JavaScript 中的文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5519368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I perform a str_replace in JavaScript, replacing text in JavaScript?
提问by Vish
I want to use str_replace
or its similar alternative to replace some text in 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");
should give
应该给
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.
如果您要使用正则表达式,与内置替换方法相比,性能有何影响。
采纳答案by TheChetan
Using regex for string replacement is significantly slower than using a string replace.
As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:
使用正则表达式进行字符串替换比使用字符串替换要慢得多。
正如在 JSPerf 上演示的那样,您可以有不同级别的效率来创建正则表达式,但所有这些都比简单的字符串替换要慢得多。正则表达式较慢,因为:
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.
固定字符串匹配没有回溯、编译步骤、范围、字符类或许多其他减慢正则表达式引擎的功能。当然有优化正则表达式匹配的方法,但我认为在常见情况下不太可能击败对字符串的索引。
For a simple test run on the JS perf page, I've documented some of the results:
对于在 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>
The results for Chrome 68 are as follows:
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
From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that .replace
only replaces the first instance of the matched character. Its only possible to replace all instances with //g
. The performance trade off and code elegance could be argued to be worse if replacing multiple instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_');
or worse while (name.includes(' ')) { name = name.replace(' ', '_') }
为了这个答案的完整性(从评论中借用),值得一提的是.replace
只替换匹配字符的第一个实例。只能将所有实例替换为//g
. 如果替换多个实例name.replace(' ', '_').replace(' ', '_').replace(' ', '_');
或更糟,则可能会认为性能权衡和代码优雅会更糟while (name.includes(' ')) { name = name.replace(' ', '_') }
回答by sdleihssirhc
You would use the replace
method:
您将使用以下replace
方法:
text = text.replace('old', 'new');
The first argument is what you're looking for, obviously. It can also accept regular expressions.
显然,第一个参数是您要查找的内容。它还可以接受正则表达式。
Just remember that it does notchange the original string. It only returns the new value.
请记住,它并不会改变原来的字符串。它只返回新值。
回答by realmag777
More simply:
更简单:
city_name=city_name.replace(/ /gi,'_');
Replaces all spaces with '_'!
用'_'替换所有空格!
回答by Lukas Liesis
All these methods don't modify original value, returns new strings.
所有这些方法都不会修改原始值,而是返回新字符串。
var city_name = 'Some text with spaces';
Replaces 1st spacewith _
用 _替换第一个空格
city_name.replace(' ', '_'); // Returns: Some_text with spaces
Replaces all spaceswith _ using regex. If you need to use regex, then i recommend testing it with https://regex101.com/
使用正则表达式用 _替换所有空格。如果您需要使用正则表达式,那么我建议您使用https://regex101.com/对其进行测试
city_name.replace(/ /gi,'_'); // Returns: Some_text_with_spaces
Replaces all spaceswith _ without regex. Functional way.
用 _替换所有空格,不带正则表达式。功能方式。
city_name.split(' ').join('_'); // Returns: Some_text_with_spaces
回答by Timon. Z
You should write something like that :
你应该写这样的东西:
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
回答by Pavel
that function replaces only oneoccurrence.. if you need to replace multiple occurrences you should try this function: http://phpjs.org/functions/str_replace:527
该函数仅替换一次出现..如果您需要替换多次出现,您应该尝试使用此函数:http: //phpjs.org/functions/str_replace: 527
Not necessarily. see the Hans Kesting answer:
不必要。见汉斯·凯斯廷的回答:
city_name = city_name.replace(/ /gi,'_');
回答by Zoyt
The code that others are giving you only replace one occurrence, while using regular expressions replaces them all (like @sorgit said). To replace all the "want" with "not want", us this code:
其他人给你的代码只替换了一次,而使用正则表达式替换了所有代码(就像@sorgit 说的那样)。要将所有“想要”替换为“不想要”,请使用以下代码:
var text = "this is some sample text that i want to replace";
var new_text = text.replace(/want/g, "dont want");
document.write(new_text);
The variable "new_text" will result in being "this is some sample text that i dont want to replace".
变量“new_text”将导致“这是我不想替换的一些示例文本”。
To get a quick guide to regular expressions, go here:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
To learn more about str.replace()
, go here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
Good luck!
要获得正则表达式的快速指南,请访问:
http: //www.cheatography.com/davechild/cheat-sheets/regular-expressions/
要了解有关 的更多信息str.replace()
,请访问:
https: //developer.mozilla.org/ en-US/docs/JavaScript/Reference/Global_Objects/String/replace
祝你好运!
回答by arbithero
hm.. Did you check replace() ?
嗯.. 你检查了 replace() 吗?
Your code will look like this
您的代码将如下所示
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
回答by arbithero
In JavaScript, you call the replace
method on the String object, e.g. "this is some sample text that i want to replace".replace("want", "dont want")
, which will return the replaced string.
在 JavaScript 中,您调用replace
String 对象上的方法,例如"this is some sample text that i want to replace".replace("want", "dont want")
,将返回替换后的字符串。
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want"); // new_text now stores the replaced string, leaving the original untouched
回答by Town
var new_text = text.replace("want", "dont want");