Replace all text except for the alt or href attribute.

I want to replace all the matched text with another text, but I do not want to replace if this text is in the alt or href attribute. Example:

 <p>Hello world!</p> <p><img src="hello.jpg" alt="Hello"/></p> Hello 

My code is:

 var replacepattern = new RegExp('Hello', 'gi'); newcontent = newcontent.replace(replacepattern, function(match, contents, offset, s) { var link = 'demo.com' index++; if (link != '') { return '<a href="' + link + '">' + match + '</a>'; } else { return match; } }); 

It only works fine with text. How can I match text except img src , alt etc.

0
source share
1 answer

You can use jQuery itself to help you with the replacement:

 $(html) .contents() .filter(function() { return this.nodeType == 1 || this.nodeType == 3; }).each(function() { this.textContent = this.textContent.replace(replacepattern, 'whatever'); }); 

Note that the last occurrence of Hello not replaced, since it is technically not valid to have the text node as a child of the <body> .

In addition, you will have to change it to work in IE <9 or 10; in principle, the browser will support node.textContent :)

Update

The problem was somewhat more complex; or maybe my mind makes it more difficult than it is. Replacing text nodes with jQuery is not an easy task, so this requires some clean JS:

 $('<div><p>Hello world!</p><p><img src="hello.jpg" alt="Hello"/></p>Hello</div>') .find('*') .andSelf() .each(function() { for (var i = 0, nodes = this.childNodes, n = nodes.length; i < n; ++i) { if (nodes[i].nodeType == 3) { var txt = nodes[i].textContent || nodes[i].innerText, newtxt = txt.replace(/Hello/g, 'Bye'); if (txt != newtxt) { var txtnode = document.createTextNode(newtxt); this.replaceChild(txtnode, nodes[i]); } } } }) .end() .end() .appendTo('body'); 
+2
source

Source: https://habr.com/ru/post/1499224/


All Articles