Replace words in string between two specific chars

I have following string and I want to replace the chars between the "[" and "]":

text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] magna"

and the goal is to get:

newText = "Lorem ipsum dolor sit amet, <a href=www.example1.com target="_blank">Link 1</a> sadipscing elitr, sed diam nonumy <a href=www.example2.com target="_blank">Link 2</a> tempor invidunt ut labore et <a href=www.example3.com target="_blank">Link 3</a> magna"

The following code replaces only the first link (link 1) but link 2 & 3 has no effect

const urlTextChain = text.substring(text.indexOf("[") + 1, text.indexOf("]"));

if (urlTextChain) {
  const textUrl = urlTextChain.substring(0, urlTextChain.lastIndexOf("|"));
  const url = urlTextChain.substring(urlTextChain.indexOf("|") + 1);
  const link = "<a href=" + url + " target=" + '"_blank"' + ">" + textUrl + "</a>";
  let newText = text.replace(urlTextChain, link);
  newText = newText.replace('[', '');
  newText = newText.replace("]", '');
  return newText;
}

>Solution :

MDN String.prototype.replace
MDN RegExp

You can use RegExp for replace.

p1 corresponds to the first parenthesis and p2 is the value corresponding to the second parenthesis.

const text =
  'Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] magna'

const convertLinkFromText = (txt) => {
  const reg = new RegExp(/\[(.*?)\|(.*?)\]/, 'gi')

  return txt.replace(reg, (match, p1, p2) => {
    return `<a href="${p2}" target="_blank">${p1}</a>`
  })
}

const newText = convertLinkFromText(text)

console.log(newText)

Leave a Reply