从字符串中删除连字符的最快方法

我的 ID 看起来像: 185-51-671,但是它们也可以在结尾处有字母 175-1-7b

我想做的就是删除连字符,作为一个预处理步骤。给我展示一些很酷的用 javascript 做这件事的方法?我想可能会有很多类似这样的问题,但我很有兴趣看看人们会为“只是连字符”提出什么样的优化

谢谢!

Edit: 我使用的是 jQuery,所以我猜

numberNoHyphens = number.replace("-","");

还有别的选择吗?

编辑 # 2:

所以,如果有人想知道的话,正确的答案是

numberNoHyphens = number.replace(/-/g,"");

你需要“ g”即模式开关或“全局标志”,因为

numberNoHyphens = number.replace(/-/,"");

将只匹配并替换第一个连字符

109848 次浏览
var str='185-51-671';
str=str.replace(/-/g,'');

You need to include the global flag:

var str="185-51-671";
var newStr = str.replace(/-/g, "");

This is not faster, 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.

http://jsperf.com/remove-hyphens-from-string

Som of these answers, prior to edits, did not remove all of the hyphens. You would need to use .replaceAll("-","")

Gets much easier in String.prototype.replaceAll(). Check out the browser support for the built-in method.

const str = '185-51-671';
console.log(str.replaceAll('-', ''));

In tidyverse, there are multiple functions that could suit your needs. Specifically, I would use str_remove, which will replace in a string, the giver character by an empty string (""), effectively removing it (check here the documentation). Example of its usage:

str_remove(x, '-')