开发者

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

开发者 https://www.devze.com 2023-01-27 07:27 出处:网络
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?

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-o开发者_StackOverflowr-9-lazy-dogs

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


str.replace(/ +/g, '-').toLowerCase();


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();


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号