Created
March 29, 2021 22:32
-
-
Save sugoidesune/ad6acfa3a46955a88b0a1dfcd392873c to your computer and use it in GitHub Desktop.
Use your regex and list-template from regexr directly in your code.
This file contains 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
function regexrList(captureRegEx, listTemplate, str) { | |
// map for every match | |
const matchesToTemplate = (match) => { | |
// replace for every group in match | |
return match.reduce((acc,group,i)=>{ | |
// 0th index is $n, others follow index number $1,$2 | |
var key = '\\$' + (i==0 ? 'n' : i) | |
var regex = new RegExp(key,'g') | |
// example: replace $1 with match[1] which is 'group' | |
var replaced = acc.replace(regex,group) | |
return replaced | |
},listTemplate) | |
}; | |
return Array.from(str.matchAll(captureRegEx), matchesToTemplate).join(""); | |
} | |
var text = `I love to hate. | |
I love to hate. | |
I love to hate. | |
I love to hate.` | |
var result = regexrList(/(love).+(hate)/g, "I $1 to $1.\n",text) | |
console.log(result) | |
// >>> "I love to love. | |
// I love to love. | |
// I love to love. | |
// I love to love. | |
// " |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment