【问题标题】:Function to replace key/value strings between brackets with custom html用自定义html替换括号之间的键/值字符串的函数
【发布时间】:2020-03-23 00:20:36
【问题描述】:

假设我有一个这样的字符串:

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

我正在尝试编写一个用 html 元素替换 {Title: url} 的函数,以返回:

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.logs 正确的 html 元素。我的大脑正在放弃,我真的很感激一些帮助......提前谢谢!

【问题讨论】:

    标签: javascript regex logic


    【解决方案1】:

    您可以使用 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;

    【讨论】:

    • 非常感谢您的回答!你能解释一下(_,m) 是什么吗?我明白这个函数在做什么,但是下划线让我有点困惑……
    • 也被const [txt, link] = m.split(': ');惊呆了,我不知道这是可能的?
    • @bruno 当然,不用担心。 (_, m) 是要替换的回调中箭头函数参数的一部分。您可以将其视为function(_, m) {...}。 replace 回调的第一个参数是正则表达式匹配的整个匹配项(其中包括 {})。第二个参数 (m) 是正则表达式中的第一个捕获组(所以在 {} 之间的所有内容)。因为我不想在我拆分的字符串中出现{},所以我忽略了第一个参数(我可以将其命名为foo 之类的任何名称——但_ 通常用于未使用的参数) .
    • @bruno 至于 const [txt, link] = ... 被称为 destructuring assignment - 绝对值得研究,因为它有很多不错的用例
    猜你喜欢
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 2017-12-02
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    相关资源
    最近更新 更多