Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to hyphen-conjoined words in JavaScript (& regex?)?

Let's say I have a string of text:

The quick brown fox jumped over 8 or 9 lazy dogs

How would you convert this to lower case hyphen-conjoined words like this?

the-quick-brown-fox-jumped-over-8-or-9-lazy-dogs

I assume it requires some kind of regex to convert it correctly?

like image 773
RegexClueless Avatar asked Nov 30 '10 02:11

RegexClueless


3 Answers

str.replace(/ +/g, '-').toLowerCase();
like image 140
deceze Avatar answered Sep 28 '22 08:09

deceze


Use \s for a space character in a regular expression, add the g flag so it replaces all occurrences, and call toLowerCase() to make the string lowercase:

str.replace(/\s/g, "-").toLowerCase();
like image 22
Alex Avatar answered Sep 28 '22 08:09

Alex


Or this: "the quick brown fox jumps over the lazy dog".split(" ").join("-");

like image 32
D. Patrick Avatar answered Sep 28 '22 07:09

D. Patrick