Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading