1
\$\begingroup\$

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.

Michael K
2,9091 gold badge22 silver badges24 bronze badges
asked Sep 8, 2011 at 11:27
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

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,'-')
answered Sep 8, 2011 at 13:16
\$\endgroup\$
1
  • \$\begingroup\$ Good call using character sets. That should actually work better than my answer. \$\endgroup\$ Commented Sep 8, 2011 at 13:31
1
\$\begingroup\$

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,"-");
answered Sep 8, 2011 at 11:48
\$\endgroup\$
3
  • \$\begingroup\$ God bless you!.. thats what I was looking for!! \$\endgroup\$ Commented 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\$ Commented 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\$ Commented Sep 8, 2011 at 12:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.