Leff
Leff

Reputation: 1360

Replacing words in text that match regex

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?

Upvotes: 0

Views: 39

Answers (1)

Eugene Voynov
Eugene Voynov

Reputation: 350

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"')

Upvotes: 1

Related Questions