【问题标题】:How iterate through text and replace a specific words如何遍历文本并替换特定单词
【发布时间】:2019-02-21 03:14:09
【问题描述】:

我正在尝试编写一个简单的函数,它遍历文本并将遇到的任何 href 替换为文本;

var REPLACE = [
    {expression: www.anyhref.com, value: 'website'}
];

function(instance) {
   instance = function {
       var insteadURL;

       insteadURL: = REPLACE.match(function(expression) {
           return element.classList.contains(expression);
       });

       return(
           insteadURL ? insteadURL.value : getElementText(expression)
       );
   }
}

我觉得我可能没有正确使用 match 方法或条件运算符,但据我所知,这应该可以工作。但当然不是。

【问题讨论】:

  • 第二个insteadURL有错别字。
  • 您的match 方法有问题,还是您正在寻找正则表达式等来匹配url/hrefs?
  • 实际上REPLACE.match 会抛出错误,因为REPLACEarray 而不是string
  • @vahdet 你能提供一个例子来指导吗?
  • 简而言之,我试图了解您被卡住的确切点。因此,我首先要了解您的具体问题,然后尝试提出解决方案。

标签: javascript conditional string-matching


【解决方案1】:

如果你想替换文本中的链接(我猜),试试这个正则表达式:

   /<a.*?href="www.anyhref.com".*?\/a>/g

然后,您必须为要替换数组中的条目的每个 href 添加。

【讨论】:

    【解决方案2】:

    如果您在 DOM 上下文中,您可以执行以下操作:

    要遍历 DOM,你可以使用这个函数:

    function domReplace(node, iterator) {
      switch (node && node.nodeType) {
      case 1: case 9: case 11: {
        const newNode = iterator((node.nodeName || '').toLowerCase(), node);
        if (newNode && newNode != node && node.parentNode) {
            node.parentNode.insertBefore(newNode, node);
            node.parentNode.removeChild(node);
        }
        for (let child = newNode.firstChild; child; child = child.nextSibling)
           domReplace(child, iterator);
      } break ;
      case 3: {
        const newNode = iterator('#text', node);
        if (newNode && newNode != node && node.parentNode) {
            node.parentNode.insertBefore(newNode, node);
            node.parentNode.removeChild(node);
        }
      } break ;
      }
    }
    

    如果模式与.href 匹配,则可以将a 替换为自定义文本:

    domReplace(document, (type, node) => {
      if (type == 'a') {
        for (let i = 0; i < REPLACE.length; i += 1)
          if (~(node.href || '').indexOf(REPLACE[i].expression))
             return document.createTextNode(REPLACE[i].value);
        return document.createTextNode(node.href);
      }
      return node;
    });
    

    注意你不应该给documentdomReplace,而是给正确的dom节点以避免整页替换

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      • 2019-10-01
      • 2016-12-26
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      相关资源
      最近更新 更多