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?
To replace the spaces with dashes in a string, call the replaceAll() method on the string, e.g. str. replaceAll(' ', '-') . The replaceAll method will return a new string where all spaces are replaced by dashes.
Replacing spaces using Find and Replace Press Ctrl + H to display the Find and Replace dialog box. You can also click the Home tab in the Ribbon and select Replace in the Find & Select group. In the Find what box, type a space. In the Replace with box, type an underscore, dash, or other value.
\s means "one space", and \s+ means "one or more spaces". But, because you're using the /g flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect. Follow this answer to receive notifications.
The return value of strtolower can be passed as the third argument to str_replace (where $string is present). The str_replace function is used to replace a set of characters/character with a different set of character/string.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With