Javascript 替换字符串中的下划线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5562574/
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
Replace underscores in string
提问by blasteralfred Ψ
I have a string var string = "my__st_ri_ng"
. I want to replace all underscores with single space and I want to store it it another variable. Each underscore should have a space replacement, which means multiple consecutive underscores should have respective number of empty spaces. I want to get my mentioned variable as my<sp><sp>st<sp>ri<sp>ng
. How can I do this using jquery??
我有一个字符串var string = "my__st_ri_ng"
。我想用单个空格替换所有下划线,我想将它存储为另一个变量。每个下划线都应该有一个空格替换,这意味着多个连续的下划线应该有各自的空格数。我想将我提到的变量作为my<sp><sp>st<sp>ri<sp>ng
. 我如何使用 jquery 做到这一点?
Thanks in advance...:)
提前致谢...:)
blasteralfred
布拉拉弗雷德
回答by kapa
What you need is Javascript's replace
function.
你需要的是Javascript的replace
功能。
var str1 = "my__st_ri_ng";
var str2 = str1.replace(/_/g, ' ');
You do not need jQuery at all for this task...
你根本不需要jQuery来完成这个任务......
回答by Anurag
To replace all occurrences of _
, use a regular expression with the g
(global) flag.
要替换所有出现的_
,请使用带有g
(全局)标志的正则表达式。
"my__st_ri_ng".replace(/_/g, " "); // "my st ri ng"
回答by VAYU
Try this...
尝试这个...
var oldStr = 'I_told_you';
var newStr = oldStr.split('_').join(' ');
回答by vbence
You don't need jQuery or even RegEx, just simple JavaSript:
你不需要 jQuery 甚至 RegEx,只需要简单的 JavaSript:
var newStr = oldStr.replace('_', ' ');