Skip to content

Instantly share code, notes, and snippets.

@sveisvei
Forked from ivarconr/regex-match-group.js
Created February 22, 2017 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sveisvei/8a495f2e2db41a768bb0bcd43e724bc4 to your computer and use it in GitHub Desktop.
Save sveisvei/8a495f2e2db41a768bb0bcd43e724bc4 to your computer and use it in GitHub Desktop.
/**
* Given we have a regex with one more matching groups.
* The regex should capture those groups from an 'input'
* string and replace the matched values in an 'template'
* string.
*
* Example:
* regex: /([1-9]{8})/([1-9]{8})?/
* input string: '/some-magic/path/12122211/22112211'
* template string: 'http://someurl?adId=$1&adId=$2'
*
* Should produce following output:
* http://someurl?adId=12122211&adId=22112211
*
* My current implementation, kinda works, but would love
* to improve the string-template updater.
*/
const re = new RegExp('/.*([1-9]{8})/([1-9]{8})?', 'g');
const input = '/some-magic/path/12122211/22112211';
const template = 'http://someurl?adId=$1&adId=$2';
console.log(input.replace(re, template));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment