Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have the following code, which replaces " " <-- Spaces with "-" <-- Dash.
Because some of the title text will be returned with more spaces, it converts it into 3 dashes.

Examples of Possible Titles:

  • "Hello  World  From  Jquery" <--- Notice 2 Spaces between the words, not 1
  • "Main Title - Sub-Title or description here"

I would like the above titles to be turned into:

  • "Hello-World-From-Jquery" <---- (Not "Hello--World--From--Jquery")
  • "Main-Title-Sub-Title-or-description-here" <--- (Not "Main-Title---Sub-Title-or-desc...")

This is what I got so far, but its not ideal as you can see. Example:

var dirty_url = ui.item.label;
var url = dirty_url.replace(/\s+/g,"-");
var url = url.replace(/---/g,"-");

So basically, I want to convert all spaces and illegal characters (Its for a url) to "-" to be used in a url. I only want a maximum of 1 dash between charactors.

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

Shouldn't this work:

var dirty_url = ui.item.label;
var url = dirty_url.replace(/[-\s]+/g,'-')

Or, for more thorough:

var url = dirty_url.replace(/[-\s@#$%^&*]+/g,'-') // etc...

Though at this point, you might just want to remove all non word characters:

var url = dirty_url.replace(/\W+/g,'-')
share|improve this answer
 
Good call using character sets. That should actually work better than my answer. –  Ryan Kinal Sep 8 '11 at 13:31
add comment

Easy enough - regular expressions have an "alternation" operator, which works a lot like an "or".

var dirty_url = ui.item.label;
var url = dirty_url.replace(/(\s+|-{2,})/g,"-");
share|improve this answer
 
God bless you!.. thats what I was looking for!! –  JustAnil Sep 8 '11 at 11:50
 
just testing, and it doesnt really solve my problem tho, still get 3 (---) when I only want 1 –  JustAnil Sep 8 '11 at 11:51
 
It looks to be working in my testing. Still, I've edited the regex to be slightly better - it will no longer replace a single dash with a single dash. –  Ryan Kinal Sep 8 '11 at 12:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.