DEV Community

Jenuel Oras Ganawed
Jenuel Oras Ganawed

Posted on

JavaScript Regex Tip: change "HelloWorldAgain" to "Hello World Again" (Camelcase to Separate Words) with Explanation

So you might also have encountered this problem were you want to transpose a camelcased 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
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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.


I hope you learn a little on This short article. If you like to read more check my Blog site here: https://blog.brojenuel.com

If you like to Give Me Coffee
I'm not stopping You: https://ko-fi.com/brojenuel

If you have GCASH heres my GCash, just scan it using your Gcash app:

Brojenuel GCash Code

Top comments (0)