Last active
February 22, 2017 19:45
-
-
Save ivarconr/175f63e3ce9f815ff36dd9de6eb53889 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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})?'); | |
const input = '/some-magic/path/12122211/22112211'; | |
const template = 'http://someurl?adId=$1&adId=$2'; | |
const match = re.exec(input); | |
let output = template; | |
if (match) { | |
for(let i=1; i<match.length; i++) { | |
if(match[i]) { | |
output = output.replace(`$${i}`, match[i]) | |
} | |
} | |
} | |
console.log(output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Trygve almost there with template strings: https://gist.github.com/trygve-lie/4255138406b9b5969ce3c5da7a0711fb