Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 754
EzzDev Avatar asked Dec 31 '09 02:12

EzzDev


People also ask

How do you replace spaces with dashes?

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.

How do I change dashes to spaces in Excel?

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.

What is /\ s +/ G?

\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.

How to convert space into in php?

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.


2 Answers

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.

like image 127
Christian C. Salvadó Avatar answered Oct 05 '22 12:10

Christian C. Salvadó


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 
like image 37
yurin Avatar answered Oct 05 '22 11:10

yurin