I've the case where I'm looping through URL array (ex. [www.stackoverflow.com, www.ex.com]
) and matching those URLs one by one with given string during loop and replacing with anchor tag to make it clickable.
I'm able to do it using JS replaceAll
method but incase of multiple occurrences of same url in given string it even matches url in tag.
For example, if given string is "Check it out at www.stack.com/abc and bookmark the www.stack.com, www.overflow.com"
and given URL array is [www.stack.com/abc, www.stack.com]
During first replace iteration it will be "Check it out at <a href="www.stack.com/abc">www.stack.com/abc</a> and bookmark the www.stack.com"
and then the problem occurs during the second iteration, it'll replace the string even in the tag. I want to ignore the html tag during the replaceAll
method. Can someone help me out with this ?
I've tried to ignore tags with the below regex but it doesn't working for content it between anchor tags.
exString.replaceAll(new RegExp(url "(?![^<>]*>)", "gi"), replaceText);
CodePudding user response:
Let's split and join then
const div = document.getElementById("text");
let str = div.textContent;
let arr = str.split(/ /)
console.log(arr)
const urls = ["www.stack.com/abc", "www.stack.com"];
arr.forEach((word,i) => {
const punctuation = word.match(/(\W$)/)
if (punctuation) word = word.slice(0,-1)
const idx = urls.indexOf(word);
if (idx !=-1) arr[i] = arr[i].replace(word,`<a href="${word}">${word}</a>`)
})
console.log(arr)
div.innerHTML = arr.join(" ")
<div id="text">Check it out at www.stack.com/abc and bookmark the www.stack.com, www.overflow.com.</div>
CodePudding user response:
Maybe you can first remove any anchors so they cannot be processed?
exString.replaceAll(/<a[^>]*>/g, '')