【问题标题】:Check string for array elements and systematically replace them with HTML tags - (JS, ReactJS)检查字符串中的数组元素并用 HTML 标记系统地替换它们 - (JS, ReactJS)
【发布时间】:2017-10-20 21:38:14
【问题描述】:

我需要搜索string,如果它有任何与我的array 匹配的值,我需要向它们添加<span></span> 标记以添加自定义CSS。我正在使用 reactJS。

  1. 如何在字符串中搜索数组中的对象? 示例:

    let string = 'this is a message with many inputs, {{input1}}, {{input2}}, and again {{input1}}' let array = [{parameter: '{{input1}}'},{parameter: '{{input2}}'},...] findAllOccurrances = () => {???}

  2. 然后系统地将'{{inputX}}'替换为<span className='bizarre-highlight'>{{inputX}}</span>

我的意图是在 div 中与我的array 匹配的任何文本中添加自定义 CSS,所以如果您有任何想法,请拍摄!同样,如果有帮助,请使用 reactJS。

【问题讨论】:

    标签: javascript html css arrays reactjs


    【解决方案1】:

    我创建了一个组件,它将用一个跨度替换需要突出显示的元素,您可以对其进行测试here

    组件是:

    import React from 'react';
    
    export default ({ terms, children }) => {
      const result = []
      const regex = terms.map(escapeRegExp).join('|');
      const re = new RegExp(regex);
      let text = (' ' + children).slice(1); // copy
      let match = re.exec(text);
      while (match != null) {
        const str = match.toString();
        result.push(text.slice(0, match.index));
        result.push(<span className="highlighted">{str}</span>);
        text = text.slice(match.index + str.length);
        match = re.exec(text);
      }
      result.push(text);
      return result;
    }
    
    function escapeRegExp (str) {
      return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&");
    }
    

    你应该像这样使用它:

    import React from 'react';
    import Highlighter from './Highlighter';
    
    const terms = [ '{{input1}}', '{{input2}}' ]
    
    const App = () => (
      <div>
        <Highlighter terms={terms}>
          {'this is a message with many inputs, {{input1}}, {{input2}}, and again {{input1}}'}
        </Highlighter>
      </div>
    );
    

    【讨论】:

    • 我需要检查一下,但它的链接是完全准确的!谢谢!!!!
    • @KevinDanikowski 如果您需要任何东西,尽管问,我很乐意为您提供帮助。
    • 嘿@kakamg0,我不断收到“警告:数组或迭代器中的每个孩子都应该有一个唯一的“关键”道具。由于添加了代码 if (allParametersQuery.allParameters &amp;&amp; (!allParametersQuery.allParameters.loading &amp;&amp; !allParametersQuery.allParameters.error)) terms= allParametersQuery.allParameters.map((parameter) =&gt; {return '{{' + parameter.param + '}}'}) ,我将 allParametersQuery 设置为我通过 terms 传递给该组件的内容。知道为什么这张地图会导致这个问题吗?
    • 我认为警告来自Highlighter 组件中的result 数组,您应该将result.push(&lt;span className="highlighted"&gt;{str}&lt;/span&gt;); 更改为result.push(&lt;span key={match.index} className="highlighted"&gt;{str}&lt;/span&gt;);。你可以阅读更多关于警告here
    • 你是个天才,谢谢! match.index 给出了重复的键,我使用了 message.length。运行良好,不会出错。
    【解决方案2】:

    使用带有正则表达式的String#replace 查找“{{inputX}}”的所有实例,并使用span 包装匹配项:

    const string = 'this is a message with many inputs, {{input1}}, {{input2}}, and again {{input3}}'
    
    const array = [{parameter: '{{input1}}'},{parameter: '{{input2}}'}]
    
    const pattern = new RegExp(array.map(({ parameter }) => parameter).join('|'), 'g');
    
    const result = string.replace(pattern, (match) => 
      `<span className='bizarre-highlight'>${match}</span>`
    )
    
    console.log(result)

    【讨论】:

      【解决方案3】:

      使用Array#map 提取值以包装在&lt;span&gt; 中,然后循环它们以进行替换:

      let string = 'this is a message with many inputs, {{input1}}, {{input2}}, and again {{input1}}';
      let array = [{parameter: '{{input1}}'},{parameter: '{{input2}}'}];
      
      array.map(el => { return el.parameter }).forEach(str => {
        string = string.split(str).join("<span className=\'bizarre-highlight\'>" + str + "</span>");
      });
          
      console.log(string);

      【讨论】:

      • 这有效并取代了我需要的东西。谢谢!它没有解决我在文本中添加 CSS 的问题,但我现在应该走在正确的道路上。
      • @KevinDanikowski 为什么不给 span 添加样式属性?
      • 说实话,我不知道这会如何改变它或你的意思。现在我正在想办法从字符串中取出跨度。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      相关资源
      最近更新 更多