简体   繁体   English

如何遍历文本并替换特定词

[英]How iterate through text and replace a specific words

I'm trying to write a simple function that iterates through text and replaces any href's it comes across with text instead; 我正在尝试编写一个简单的函数,该函数可遍历文本并替换文本所遇到的所有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)
       );
   }
}

I feel as though I may not be using the match method or the conditional operator properly but from what I understand this should work. 我觉得好像我可能没有正确使用match方法或条件运算符,但据我所知这应该起作用。 But of course it doesn't. 但是,当然不是。

If you're trying to replace links (i guess) in your text, try this regex: 如果您要替换文本中的链接(我想),请尝试以下正则表达式:

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

Then you would have to add for each href you want to replace an entry in your array. 然后,您将必须为每个要替换数组中的条目的href添加。

If you are in DOM context you can do the following: 如果您在DOM上下文中,则可以执行以下操作:

To iterate through the DOM you can use this function: 要遍历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 ;
  }
}

Then you can replace a if pattern matches .href with custom text: 然后,您可以将if模式匹配.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;
});

Note you should not give document to domReplace but the right dom node to avoid full page replacement 请注意,您不应将documentdomReplace而应将document给dom节点,以避免整个页面的替换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM