Skip to content Skip to sidebar Skip to footer

Js Regex: Replace Words Not In A Span Tag

For example: var htmlString = 'It's a nice day and also a sunny day, it's day for surfing.'; want to replac

Solution 1:

Here is how you can achieve that with a DOM-based approach:

function textNodesUnder(el){
  var n, walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  while(n=walk.nextNode())
  {
       if (n.parentNode.nodeName.toLowerCase() !== 'span' ||
          (n.parentNode.nodeName.toLowerCase() === 'span' &&
           n.parentNode.getAttribute("title") !== 'mark'))
      		n.nodeValue =  n.nodeValue.replace(/\bday\b/g, "night"); 
  }
  return el.firstChild.innerHTML;
} 

function replaceTextNotInSpecificTag(s) {
  var doc = document.createDocumentFragment();
  var wrapper = document.createElement('myelt');
  wrapper.innerHTML = s;
  doc.appendChild( wrapper );
  return textNodesUnder(doc);
}

var s = "It's a <span title='mark'>nice day</span> and also a <span title=''>sunny day</span>, it's day for <span>surfing day</span>.";
console.log(replaceTextNotInSpecificTag(s));

Result:

It's a <span title="mark">nice day</span> and also a <span title="">sunny night</span>, it's night for <span>surfing night</span>.

First, we create a document fragment, then create an element myelt, then append it as a child to the document fragment allowing us to access the DOM nodes with a dom parser.

Then, using document.createTreeWalker with SHOW_TEXT filter we get access to all text nodes. We walk the nodes, and if the node name is not span or if it is a span tag with a title attribute whose value is not equal to "mark", we perform a search and replace.


Post a Comment for "Js Regex: Replace Words Not In A Span Tag"