We can use a combination of
.replace with a regex and
.toLowerCase to convert a string into lowercase and replace spaces as well in the following way:
const string = 'String to Kebab Case' // Results: “string-to-kebab-case” const kebab = string.replace(/\W+/g, '-').toLowerCase() // Results: “string_to_kebab_case” const snake = string.replace(/\W+/g, '_').toLowerCase()
There are two things to note here for the regex:
- First, we used the "not word" selector, which will match any character that is not a word. (notice that we have used a plus sign to match 1 or more words)
- Secondly, we used the
g(global) flag to match more for multiple results.
This will select the whitespaces, which then we can replace with either a dash or an underscore, depending on whether we want to go with kebab-case or snake-case. This also works with multiple whitespaces, as well as other signs that should be stripped from the end string, such as the following:
'String with multiple spaces' -> 'string-with-multiple-spaces' 'A & B' -> 'a-b'
Hence, it is more flexible than using the whitespace character (
\s). Did you know you can also use variables inside regular expressions to create dynamic expressions? Check out the following tutorial:
- Access exclusive interactive lessons
- Unlimited access to hundreds of tutorials
- Remove ads to learn without distractions