Advanced use case of RegEx in JavaScript
Published on: 28th Jul 2024
Overview
RegEx is very powerful and here's an example of a trick in using RegEx.
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:
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.
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:
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
- For a other complex usage of RegEx, please refers to one of the earlier post: Parsing CREATE TABLE statement with Regex in Node.js
- Use case of RegEx in JavaScript.
Jump to #JAVASCRIPT blog
Jump to #NODEJS blog
Author
Lau Hon Wan, software developer.