【问题标题】:How to loop through a string for a regex match, concat return new full string如何遍历字符串以进行正则表达式匹配,concat返回新的完整字符串
【发布时间】:2018-11-13 21:02:32
【问题描述】:

我正在努力实现:

const finalStr = "team='Core', team='Mechanics'"
//loop through string, get single quotes, add <bold>'Core'</bold>
//I want to return the string: 
"team=<bold>'Core'</bold>, team=<bold>'Mechanics'</bold>"

我已经尝试过,但显然是错误的……无法理解:

const finalStr = this.state.finalString
const newFinal = finalStr.match(/'(.*?)'/g).map(item => {
    item = item.replace(item, '<b>' + item + '</b>')
      return item;
    });

【问题讨论】:

  • 无需循环,只需replace一次:replace(/.../g, '&lt;b&gt;$&amp;&lt;/b&gt;')
  • 你想用它来生成 HTML 吗?如果是这样,正确的标签是&lt;b&gt;,而不是&lt;bold&gt;,因为该标签不存在。
  • 感谢@georg 完美!我像往常一样把它复杂化了。

标签: javascript regex dictionary match


【解决方案1】:

您不需要回调或任何其他函数,只需使用 String.replace() 文档中描述的 replacement pattern 插入匹配的子字符串 ($&amp;)。除非您打算对匹配项做其他事情,否则您也不需要捕获组的括号。

const finalStr = "team='Core', team='Mechanics'"

const newFinal = finalStr.replace(/'.*?'/g, '<bold>$&</bold>')
console.log(newFinal)

附带说明,HTML 中没有 &lt;bold&gt; 标签,因此如果您尝试创建有效的 HTML,您应该使用 &lt;b&gt;

【讨论】:

    【解决方案2】:

    您可以使用相同的基本正则表达式/'.*?'/gi,并将自定义“替换器”回调传递给string#replace 方法来解决此问题:

    const input = "team='Core', team='Mechanics'"
    
    const output = input.replace(/'.*?'/gi, function(matchStr) {
    
      // Wrap each match in the resulting string with <bold /> tags 
      return '<bold>' + matchStr + '</bold>';
    });
    
    console.log(output);

    【讨论】:

    • 原始尝试中的正则表达式会捕获多词项,但使用\w 会阻止这种情况,因此不会产生完全相同的结果。 OP 没有将其指定为要求,但可能需要注意。
    • @Herohtar 感谢您的反馈 - 非常好,我只关注 OP 中的输入数据,并没有考虑到空格等的可能性。再次感谢!跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 2012-03-11
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 2020-04-24
    相关资源
    最近更新 更多