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?
This question is related to
javascript
string
replace
@CMS's answer is just fine, but I want to note that you can use this package: https://github.com/sindresorhus/slugify, which does it for you and covers many edge cases (i.e., German umlauts, Vietnamese, Arabic, Russian, Romanian, Turkish, etc.).
You can also use split
and join
:
"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games
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
var str = "Tatwerat Development Team";_x000D_
str = str.replace(/\s+/g, '-');_x000D_
console.log(str);_x000D_
console.log(str.toLowerCase())
_x000D_
Source: Stackoverflow.com