I am trying to run rewrites of the html of a website using a regex, and I was wondering how I can replace 'href="any letter' with 'href="https://test.com/any letter'
for example, href="helloworld.html" would turn into href="https://test.com/helloworld.html" but href="/helloworld.html" wouldn't be changed since there isn't a letter directly after.
CodePudding user response:
Since you should never use RegExp to parse or modify HTML
You can do it using the available DOM methods:
document.querySelectorAll('[href="helloworld.html"]').forEach(el => el.setAttribute("href", "https://test.com/helloworld.html"));
<a href="helloworld.html">Change my href</a>
<br>
<a href="foobar.html">Don't change my href</a>
You could use Regex, but only once you retrieved that specific href
attribute value:
document.querySelectorAll('a').forEach(el => {
const href = el.getAttribute("href");
// Finally some Regex:
const isHelloWorld = /^helloworld.html$/.test(href);
console.log(`${href} has helloWorld.html? ${isHelloWorld}`);
// Just, never use this example on data-* attributes,
// unless you have absolute control over the data-* attribute value.
});
<a href="helloworld.html">Change my href</a>
<br>
<a href="foobar.html">Don't change my href</a>