jQuery - 替换字符串中字符的所有实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13574980/
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
jQuery - replace all instances of a character in a string
提问by thednp
This does not work and I need it badly
这不起作用,我非常需要它
$('some+multi+word+string').replace('+', ' ' );
always gets
总是得到
some multi+word+string
it's always replacing for the first instance only, but I need it to work for all + symbols.
它总是只替换第一个实例,但我需要它为所有 + 符号工作。
回答by Guffa
You need to use a regular expression, so that you can specify the global (g) flag:
您需要使用正则表达式,以便您可以指定全局 (g) 标志:
var s = 'some+multi+word+string'.replace(/\+/g, ' ');
(I removed the $()
around the string, as replace
is not a jQuery method, so that won't work at all.)
(我删除了$()
字符串周围的,因为replace
它不是 jQuery 方法,所以根本不起作用。)
回答by Madbreaks
'some+multi+word+string'.replace(/\+/g, ' ');
^^^^^^
'g' = "global"
'g' = “全局”
Cheers
干杯
回答by phyatt
RegEx is the way to go in most cases.
在大多数情况下,RegEx 是可行的方法。
In some cases, it may be faster to specify more elements or the specific element to perform the replace on:
在某些情况下,指定更多元素或特定元素来执行替换可能会更快:
$(document).ready(function () {
$('.myclass').each(function () {
$('img').each(function () {
$(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
})
})
});
This does the replace once on each string, but it does it using a more specific selector.
这对每个字符串执行一次替换,但它使用更具体的选择器来执行。