My goal it to loop through a set of given elements, and replace there inner HTML with a linkifying Regex so I can convert HTML text in the form of http://*.*/* into <a href="http://*.*/*" target="_blank">http://*.*/*</a>
So I’m running a bit of vanilla javascript:
for (var i = 0; i < document.getElementsByClassName('title').length; i++) {
var title = document.getElementsByClassName('title')[i]
title.innerHTML = title.innerHTML.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,"<a target='_blank' href='$1'>$1</a>")
}
Here’s just the RegExp I’m using:
/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig
So, why on earth would this loop cause the browser to hang? The loop is over text no longer than 256 characters and there are usually between 5 and 30 .title elements, definitely not the levels of data that would crash/hang a browser. I’ve only experienced it in Chrome/Safari, unsure if it happens in Firefox/Opera or not.
Try storing results.
If the hanging continues, it’s probably because the regex is matching stuff you’ve already replaced. Try adding a negative lookahead to ensure there is no single quote immediately after the URL you are matching.
(?=!')