Sometimes, we want to convert a camel-case string to dashes in JavaScript.
In this article, we’ll look at how to convert a camel-case string to dashes in JavaScript.
How to convert a camel-case string to dashes in JavaScript?
To convert a camel-case string to dashes in JavaScript, we can use the string’s replace
method.
For instance, we write:
const camel = 'fooBar'
const dashed = camel.replace(/[A-Z]/g, m => "-" + m.toLowerCase());
console.log(dashed)
to call camel.replace
with a regex to match all capital letters.
And then we pass in a callback that replace the matches with a dash and the matched letter converted to lower case concatenated to it.
As a result, dashed
is "foo-bar"
.
Conclusion
To convert a camel-case string to dashes in JavaScript, we can use the string’s replace
method.