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.
2 Answers 2
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,'-')
-
\$\begingroup\$ Good call using character sets. That should actually work better than my answer. \$\endgroup\$Ryan Kinal– Ryan Kinal2011年09月08日 13:31:23 +00:00Commented Sep 8, 2011 at 13:31
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,"-");
-
\$\begingroup\$ God bless you!.. thats what I was looking for!! \$\endgroup\$Anil– Anil2011年09月08日 11:50:11 +00:00Commented Sep 8, 2011 at 11:50
-
\$\begingroup\$ just testing, and it doesnt really solve my problem tho, still get 3 (---) when I only want 1 \$\endgroup\$Anil– Anil2011年09月08日 11:51:27 +00:00Commented Sep 8, 2011 at 11:51
-
\$\begingroup\$ 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. \$\endgroup\$Ryan Kinal– Ryan Kinal2011年09月08日 12:02:44 +00:00Commented Sep 8, 2011 at 12:02