Replace spaces with dashes and make all letters lower-case

Replace spaces with dashes and make all letters lower-case

I need to reformat a string using jQuery or vanilla JavaScript
Let’s say we have “Sonic Free Games”.
I want to convert it to “sonic-free-games”.
So whitespaces should be replaced by dashes and all letters converted to small letters.
Any help on this please?

Solutions/Answers:

Solution 1:

Just use the String replace and toLowerCase methods, for example:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"

Notice the g flag on the RegExp, it will make the replacement globally within the string, if it’s not used, only the first occurrence will be replaced, and also, that RegExp will match one or more white-space characters.

Solution 2:

Above answer can be considered to be confusing a little.
String methods are not modifying original object. They return new object.
It must be:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase(); //new object assigned to var str

Solution 3:

You can also use split and join:

"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games
Related:  Auto-number table rows?