I am trying to implement regex that I found here. I would like to find any http
, https
or web a tags
and then just add target="blank" to them. So, the code looks like this:
const urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
return this.node.body.replace(urlRegex, function(url) {
return `${url}" target="blank">`;
})
And if I get a text like this:
<p>
<a href='www.norden.org'>Nordens</a>
</p>
<p>
<figure>
<img src='http://tornado-node.net/wp-content/uploads/2017/08/Ove-Hansen.jpg' alt=' Styreleder Ove Hansen. Foto: Arne Walderhaug' />
<figcaption>Ove Hansen, styreleder i Norden</figcaption>
</figure>
</p>
<p>
<a href='http://norden.org/documents.html'>norden.org</a>
</p>
This is the result from the above function:
<p>
<a href='<a href=\"www.norden.org'>Nordens</a>
</p>
<p>
<figure>
<img\" target=\"blank\"> src='<a href=\"http://tornado-node.net/wp-content/uploads/2017/08/Ove-Hansen.jpg'\" target=\"blank\"> alt=' Styreleder Leif-Ove Hansen. Foto: Arne Walderhaug' />
<figcaption>Ove Hansen, styreleder i Norden</figcaption>
</figure>
</p>
<p>
<a href='<a href=\"http://norden.org/documents.html'>norden.org</a></p>\" target=\"blank\">"
What is the correct way to implement this?
Update
I am also trying with finding the href in the text like this:
let str = this.node.body;
const regex = /(href=\')([^\']*)(\')/g;
if (str.match(regex)) {
for(let i = 0; i < str.match(regex).length; i++) {
let url = str.match(regex)[i] + ' target="_blank"';
}
}
And that gives me an array with strings that match href but and I add target="_blank"
to it, but how can I replace that now with inside the text that I am checking?