Home > database >  JS replace string using regex
JS replace string using regex

Time:06-24

I have an html as a string in JS variable. Lets say:

str = "<html>
...
<img src="/path/a.jpg">
<img src="b.png">
<img src="https://some url">
<img src="http://some url">
...
";

I want to replace all urls inside src if it does not start with http, https. for example, I want to replace:

<img src="b.png">

with

<img src="myurl/b.png">    

and

<img src="/path/xyz/b.png">

with

<img src="myurl/path/xyz/b.png">

I do not want to replace if it already starts with http or https like:

<img src="http://someurl"/>

CodePudding user response:

You can use replace()

console.log(`<img src="/path/xyz/b.png">`.replace(`src="`, `src="myurl`));

CodePudding user response:

Don't use regex for this, as this will eventually backfire (things get changed in non-img elements, in comments, in scripts, in attributes, ...), but do this with some DOM Parser. For instance the Web API has DOMParser, and nodejs has jsdom et al:

var str = `<html><body>
<img src="/path/a.jpg">
<img src="b.png">
<img src="https://some url">
<img src="http://some url">
</body></html>
`;
const {body} = new DOMParser().parseFromString(str, "text/html");
for (const img of body.querySelectorAll("img[src]")) {
    if ((img.getAttribute("src").split(":")[0]   "s").slice(0, 5) !== "https") {
        img.setAttribute("src", img.getAttribute("src").replace(/^\/?/, "myUrl/"));
    }
}
console.log(body.innerHTML);

CodePudding user response:

You can use the String.prototype.replaceAll method to do this.

const regex = new RegExp('^https?:\/\/','g')
const str = "<img src=https://testing.com/>"
str.replaceAll(regex, yourUrl)
  • Related