I am trying to replace all words in my text that match a give regex. I have made a function that looks like this:
const str = this.node.body;
const regex = /(href=\')([^\']*)(\')/g;
let newStr;
if (str.match(regex)) {
for(let i = 0; i < str.match(regex).length; i++) {
let url = str.match(regex)[i] + ' target="_blank"';
newStr = str.replace(str.match(regex)[i], url);
}
}
But, this is not right, since only the last value of the matching string will be replaced in the newStr
, since in the loop is always taking the text from the str variable, how can I make it so that I loop through updated newStr
, and replace all the values that match regex
?