bruno
bruno

Reputation: 429

Function to replace key/value strings between brackets with custom html

Say I have a string like this:

Hello World, here are the links to {my Twitter: https://twitter.com/twitter} and to {Google: https://google.com}

I'm trying to write a function that replaces the {Title: url} with a html element, to return this:

Hello world, here are the links to <a href="twitter.com/twitter">my Twitter</a> and to <a href="https://google.com>Google</a>

what I've come up with so far is

function processWithRegex(string) {
  let links = []
  let regex = /[^{\}]+(?=})/g
  let matches = string.match(regex)
  matches.forEach((match) => {
    match = match.split(': ')
    links.push(match)
  })
  links.forEach((link) => {
    html = `<a href='${link[1]}'>${link[0]}</a>`
    console.log(html)
  })
  return string
}

which, obviously, returns the input string, but at least console.logs correct html elements. My brain is giving up and I would really appreciate some help… Thanks in advance!

Upvotes: 1

Views: 156

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50954

You can make use of JavaScript's .replace() function. Since you want to replace each {txt: link} occurrence, you can create a regular expression which matches this pattern and groups everything between the { and }. Using the callback for the .replace() method, you can then .split(': ') to get the text and the link components, which you can then return as part of a link:

function processWithRegex(string) {
  let regex = /\{([^\}]*)\}/g;
  let new_str = string.replace(regex, (_,m) => {
    const [txt, link] = m.split(': ');
    return `<a href="${link}">${txt}</a>`;
  });
  return new_str;
}

const to_parse = "Hello World, here are the links to {my Twitter: https://twitter.com/twitter} and to {Google: https://google.com}";
const parsed = processWithRegex(to_parse);
console.log(parsed);

document.body.innerHTML = parsed;

Upvotes: 1

Related Questions