Функция для замены строк ключа / значения в скобках на пользовательские html - PullRequest
1 голос
/ 23 марта 2020

Скажем, у меня есть такая строка:

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

Я пытаюсь написать функцию, которая заменяет {Title: url} элементом html, чтобы вернуть это :

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

Я до сих пор придумал

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
}

, который, очевидно, возвращает входную строку, но по крайней мере console.log правильные html элементы. Мой мозг сдался, и я был бы очень признателен за помощь ... Заранее спасибо!

1 Ответ

1 голос
/ 23 марта 2020

Вы можете использовать функцию JavaScript .replace(). Поскольку вы хотите заменить каждое вхождение {txt: link}, вы можете создать регулярное выражение, которое соответствует этому шаблону и группирует все между { и }. Используя обратный вызов для метода .replace(), вы можете .split(': ') получить текст и компоненты ссылки, которые затем можно будет вернуть как часть ссылки:

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