Replacing all urls in a div

I am trying to write javascript code to find all urls inside a div. Now it would be pretty easy if all the URLs in the div were separated by spaces, in which case I can simply create a regular expression for what's inside the div to find them. However, the URLs of this outer div can be in a sub div (or any other html tag), and I also want to treat subdivs as separators (and I don't want to get rid of these subdivs). To give an example, below I want to find www.foo.com and www.bar.com in a div with the identifier "external":

<div id="outer"><div>www.foo.com</div>www.bar.com</div> 

What would be a good way to do this?

+6
source share
3 answers

You can apply a recursive call to all non-text child nodes.

 function replaceWwwInNodes(node) { //text node if (node.nodeType === 3) { node.textContent = node.textContent.replace(/* ??? */) } else { Array.prototype.forEach.call(node.childNodes, function (elem) { replaceWwwInNodes(elem); }); } } replaceWwwInNodes(document.getElementById('outer')); 

http://jsfiddle.net/UDX5V/

+3
source

Try using this sample http://jsfiddle.net/iklementiev/TaCx9/1/

 var data = document.getElementById("outer").innerText; var myRe = /www\.[0-9a-z-]+\.[az]{2,4}/igm; var matches= data.match(myRe) for (var i = 0; i < matches.length; i++) { alert('match: ' + matches[i]); } 

this help will help find all the urls.

0
source

try it

 var expression = /[ -a-zA-Z0-9@ :%_\+.~#?&//=]{2,256}\.[az]{2,4}\b(\/[ -a-zA-Z0-9@ :%_\+.~#?&//=]*)?/gi; var regex = new RegExp(expression); var regContent = $("#outer").html(); var newContent = regContent; if(regContent.match(regex)) { var textContent = regContent.match(regex); for(var i=0;i<regContent.match(regex).length;i++) { newContent = newContent.replace(new RegExp(regContent.match(regex)[i], "g"), "test"); } $("#outer").html(newContent); } 

this will get all url content and replace it as a "test".

0
source

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


All Articles