JavaScript - the advanced use case for RegEx on complex text processing


Overview

We heard RegEx is very powerful and most of the time we use RegEx on validating phone number, ID or postal code which does not seem to be complex. In fact, it's difficult to find advanced example. We found an advanced case in using RegEx but we rarely use.

Use case

For a simple case where we want to replace the first matching character with 'X and we may write the code like this:

let a = 'abcad';
a.replace(/a/, 'X');

//output: Xbcad

Sometimes, we thought it has the same behavior like other programming which replaces all 'a' with 'X'. In fact, JavaScript String.prototype.replace() with RegEx requires using 'g' flag so that the matching process is processing matching the whole string instead of just the first matching character. To do that, we need to write like this: /a/g. This means, it should find the character 'a' in the whole ('g') string. The following code will achieve this objective.

let a = 'abcad';
a.replace(/a/g, 'Y');

//output: YbcYd

For a more complex string replacement while keeping the original character, it will be look like this:

let a = 'abcad';
a.replace(/(a|b)/g, 'Z$1');

//output: ZaZbcZad

Basically, the above code tells the RegEx engine to look for either 'a' or 'b' and group them into 'group 1' (represented by '$1'). Then, the character of 'Z' will be put together with '$1' where '$1' could be 'a' or 'b'. As a result, this achieves inserting a new character while keeping the existing character.

Conclusion

Complex enough?

Related posts

Back to #JAVASCRIPT blog

Back to #NODEJS blog

Back to #blog listing