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

Henson
  • 5,563
  • 12
  • 46
  • 60

2 Answers2

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...

glmxndr
  • 45,516
  • 29
  • 93
  • 118
  • thanks! that's what i need. by the way what does /ig mean? g i assume is global right? so what is i? – Henson Feb 21 '11 at 09:21
  • 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. – glmxndr Feb 21 '11 at 11:00
  • 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 ;) – Piskvor left the building Feb 21 '11 at 16:55
  • 1
    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 : http://stackoverflow.com/questions/990904/javascript-remove-accents-in-strings – glmxndr Feb 21 '11 at 18:16
1

I think you can simplify your whole function:

yourString.toLowerCase().replace(/\W+/g, '-')
Alexey Lebedev
  • 11,988
  • 4
  • 39
  • 47