Advanced Find and Replace

To see another way capturing groups can be useful, let’s think back to Listing 5.9 of the last chapter. That was the one where we updated the age attribute of the author string with the long, complex code. We can improve that long, complex code a lot by using a regular expression with a capturing group and also using advanced find and replace (see Listing 6.25).

Listing 6.25 Improving the String Data Structure with a Capturing Group

var author = 'firstName=Steven&lastName=Foote&age=27&favoriteFoods=waffles,Thaicurry';// Use the String's built-in replace method.author.replace(/(age=)(\d+)/, function(fullMatch, group1, group2) {  /**    * fullMatch contains "age=27"    * group1 contains "age=" ...

Get Learning to Program now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.