Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to remove hyphens from a string

Tags:

javascript

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

like image 230
sova Avatar asked Jun 01 '11 16:06

sova


People also ask

How do I remove a hyphen from a string in Python?

You can just iterate through with a for loop and replace each instance of a hyphen with a blank. This code should give you a newlist without the hyphens.

How do I find a dash in a string?

You can check the count of dashes in a string with: if str. Count(x => x == '-') !=


2 Answers

You need to include the global flag:

var str="185-51-671"; var newStr = str.replace(/-/g, ""); 
like image 77
James Hill Avatar answered Oct 06 '22 07:10

James Hill


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

like image 20
Cristian Sanchez Avatar answered Oct 06 '22 09:10

Cristian Sanchez