Javascript 从字符串中删除连字符的最快方法 [js]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6204867/
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
fastest way to remove hyphens from a string [js]
提问by sova
I have IDs that look like: 185-51-671but they can also have letters at the end, 175-1-7b
我的 ID 看起来像:185-51-671但它们也可以在末尾有字母,175-1-7b
All I want to do is remove the hyphens, as a pre-processing step. Show me some cool ways to do this in javascript? I figure there are probably quite a few questions like this one, but I'm interested to see what optimizations people will come up with for "just hyphens"
我想要做的就是删除连字符,作为预处理步骤。告诉我一些很酷的方法来在 javascript 中做到这一点?我认为可能有很多这样的问题,但我很想知道人们会为“只是连字符”提出哪些优化
Thanks!
谢谢!
edit: I am using jQuery, so I guess .replace(a,b) does the trick (replacing a with b)
编辑:我正在使用 jQuery,所以我猜 .replace(a,b) 可以解决问题(用 b 替换 a)
numberNoHyphens = number.replace("-","");
any other alternatives?
还有其他选择吗?
edit #2:
编辑#2:
So, just in case anyone is wondering, the correct answer was
所以,以防万一有人想知道,正确的答案是
numberNoHyphens = number.replace(/-/g,"");
and you need the "g" which is the pattern switch or "global flag" because
并且您需要作为模式开关或“全局标志”的“g”,因为
numberNoHyphens = number.replace(/-/,"");
will only match and replace the first hyphen
只会匹配并替换第一个连字符
回答by James Hill
You need to include the global flag:
您需要包含全局标志:
var str="185-51-671";
var newStr = str.replace(/-/g, "");
回答by Cristian Sanchez
This is notfaster, but
这不是更快,而是
str.split('-').join('');
should also work.
也应该工作。
I set up a jsperf test if anyone wants to add and compare their methods, but it's unlikely anything will be faster than the replace
method.
如果有人想添加和比较他们的方法,我会设置一个 jsperf 测试,但不太可能比该replace
方法更快。
回答by Trey
var str='185-51-671';
str=str.replace(/-/g,'');
回答by Doug Chamberlain
Som of these answers, prior to edits, did not remove all of the hyphens. You would need to use .replaceAll("-","")
在编辑之前,其中一些答案并未删除所有连字符。你需要使用.replaceAll("-","")