Go Back Buy Me A Coffee 😇

JavaScript Regex Tip

/ So you might also have encountered this problem where you want to transpose camel-cased words into space-separated words, well here it is.

#javascript
#regex
#tip
✍️ BroJenuel
Mar. 13, 2023. 2:42 PM

So you might also have encountered this problem where you want to transpose camel-cased words into space-separated words, well here it is.


const words = "HelloWorldAgain".replace(/([a-z0-9])([A-Z])/g, "$1 $2");

console.log(words)

// output: Hello World Again

Let me explain that way you understand what is happening here.

We used the .replace(arg1, arg2). The first argument is what were going to find. The second argument will replace what we found.

We used a regex /([a-z0-9])([A-Z])/g. This means where going to find 2 group, () means a capture group. As you can see we have 2 group ([a-z0-9]) and ([A-Z]). So this means it will look small/numbers and capital that is together like aB or 6B.

Next we have this "$1 $2". so we explained a while ago about the regex capture groups. So $1 will represent the group 1, and $2 represents the group 2. So for example aB it will be a B, beause our second argument which is "$1 $2" has space between. Another example:

`yourTheBest`.replace(/([a-z0-9])([A-Z])/g, "$1-$2");
// output: 'your-The-Best'

This is because our separator is dashed between "$1-$2". So if we like to add more groups we can add $3 to represent the 3rd group. example:

`yourTheB1est`
.replace(/([a-z0-9])([A-Z])([0-9])/g, "$1-$2 $3");

// output: 'yourThe-B 1est'

So in the above code we added another group which is ([0-9]) and it will find 0 to 9 character. So if it will find this characters together in order based on the group it will replace based on the format we types which is "$1-$2 $3" so it becomes 'yourThe-B 1est'. It ignored the yourThe because it has no number after the T.


If you enjoy this article and would like to show your support, you can easily do so by buying me a coffee. Your contribution is greatly appreciated!

Buy Me a Coffee at https://www.buymeacoffee.com