Fastest way to remove hyphens from a string

Javascript

Javascript Problem Overview


I have IDs that look like: 185-51-671 but they can also have letters at the end, 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"

Thanks!

edit: I am using jQuery, so I guess .replace(a,b) does the trick (replacing a with b)

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

any other alternatives?

edit #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

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

will only match and replace the first hyphen

Javascript Solutions


Solution 1 - Javascript

You need to include the global flag:

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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('-', ''));

Solution 5 - Javascript

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

Solution 6 - Javascript

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, '-') 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsovaView Question on Stackoverflow
Solution 1 - JavascriptJames HillView Answer on Stackoverflow
Solution 2 - JavascriptCristian SanchezView Answer on Stackoverflow
Solution 3 - JavascriptTreyView Answer on Stackoverflow
Solution 4 - JavascriptPenny LiuView Answer on Stackoverflow
Solution 5 - JavascriptDoug ChamberlainView Answer on Stackoverflow
Solution 6 - JavascriptSebastian View Answer on Stackoverflow