skip to Main Content

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;
}

3

Answers


  1. This is a classic case for regular expression. Do this instead:

    const orig = '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 final = orig.replace(/[([^|]]+)|([^]]+)]/g, '<a href="$2" target="_blank">$1</a>');
    

    Will resolve to:

    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
    
    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
  3. You can use the replaceAll method, which uses the same semantics as the replace method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search