2

How do I replace a string that contains --- to - ?

For example :

Vision & Mission

I've managed to replace space and other special characters to - and lower case the text, so the string becomes :

vision---mission

now i need another replace to replace --- to -

Of course, that should be flexible. So for example when user inputs Vision& Mission (typo intended) the replacing will generate vision--mission (two dashes), so in that case I will need to replace -- to -

so basically I need a replace technique to replace an undetermined number of dashes to only 1 dash.

Thanks

3
  • Wait, are you trying to replace a single em-dash character (), or three dash characters (---)? Your question and its title disagree. Commented Feb 21, 2011 at 9:10
  • three dash characters. must have been the auto formatting in title text. i inputted three dash characters in the title. Commented Feb 21, 2011 at 9:24
  • Hmm, looks like it: in the edit window, they are again three dashes. Commented Feb 21, 2011 at 16:47

2 Answers 2

8

Use replace with a regexp telling to replace all sequences of dashes by a single dash.

"my--string".replace(/-+/g, "-"); // => "my-string"

Note that you could do that from the beginning, when you replace all the special characters and spaces by a dash. For example, the regexp literal /[^a-z0-9]+/ig finds all sequences of non alphanumeric characters.

"Smith & Wesson".replace(/[^a-z0-9]+/ig, "-"); // => "Smith-Wesson"

Then you just need to .toLowerCase() your string...

Sign up to request clarification or add additional context in comments.

4 Comments

thanks! that's what i need. by the way what does /ig mean? g i assume is global right? so what is i?
The 'i' flag means case insensitive. If you didn't put it, you would need to write /[^A-Za-z0-9]+/ig (with explicit capital letters). 'g' flag is for global indeed.
Are you sure that nothing éxčëpť a-zA-Z0-9 cóůld be an alphanumeric character? Poor Kurt Gödel - he'll become Kurt-G-del. Not all alphabetic characters are encoded by ASCII. +0 in total ;)
If the aim is to generate an ID without any accentuated character, you may use the code from this question before removing the special characters : stackoverflow.com/questions/990904/…
1

I think you can simplify your whole function:

yourString.toLowerCase().replace(/\W+/g, '-')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.