JSFiddle - React, Tailwind, and code Playground
by Lauro Moraes
JavaScript
const domparser = new DOMParser();
const regex = /<a.*<\/a>\(.*\)/g;
let stringParsed = '<a href="../">Voltar</a>(class="patinho-feio") qualquer coisa aqui <a href="https://hiperlynk" title="title">Cool Text</a>(class="ext-link-icon" data-super="..." foo="bar")'.replace(regex, wholeMatch => {
let domparsed = domparser.parseFromString(wholeMatch, "text/html"),
links = domparsed.getElementsByTagName('a'),
finalStr = ''
for(const l of links) {
let nxSbl = l.nextSibling.nodeValue
nxSbl.replace(/\((.+=".+" ?)+\)/, (match, $1) => {
for (let m of [...$1.match(/[^\s=]+(=["][^"]*["])?/g)]) {
let s = m.replaceAll('"', '').split('=')
l.setAttribute(s[0], s[1])
// is outside target
if ( !l.href.includes(window.location.hostname) /*@REVISE-*/ ) {
l.setAttribute('target','about:blank')
l.setAttribute('rel', 'noopener noreferrer')
}
}
})
if ( nxSbl.length > 0 ) {
finalStr += l.outerHTML + nxSbl.replace(/\((.+=".+" ?)+\)/,'')
}
}
return finalStr
})
document.body.innerHTML = stringParsed
console.log(stringParsed)