0

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?

Leff
  • 1,968
  • 24
  • 97
  • 201
  • 1
    I think this has been answered here: https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript – Sergio Baidon Sep 28 '17 at 14:12

1 Answers1

1

This works fine

Look at String.prototype.replace definition

const str   = this.node.body;
const regex = /(href=\')([^\']*)(\')/g;
let newStr = str.replace(/(href=\')([^\']*)(\')/g, '$& target="_blank"')
Eugene Voynov
  • 350
  • 4
  • 11