I have the following string,
Some text ![test1](assets/image1.png) \n some text ![test2](https://example.com/assets/image2.png) some other text \n ![test3](assets/image3.png)
I want to replace all the relative image paths i.e. assets/image1.png
to https://example.com/assets/image1.png
and same for assets/image3.png
. But we need to ignore https://example.com/assets/image2.png
as it is already absolute path.
So far I have been able to do the following,
const getImagesWithAbsolutePath = (text, absolutePathPrefix) => {
if (!text) return ''
const regex = /(\!\[.*\]\()(.*)(\))/g
return text.replace(regex, '$1' + absolutePathPrefix + '/$2?raw=true$3')
}
myText = "Some text ![test1](assets/image1.png) \n some text ![test2](https://example.com/assets/image2.png) some other text \n ![test3](assets/image3.png)";
myDomain = "https://example.com";
console.log(getImagesWithAbsolutePath(myText, myDomain));
As you can see the output is,
Some text ![test1](https://example.com/assets/image1.png?raw=true)
some text ![test2](https://example.com/https://example.com/assets/image2.png?raw=true) some other text
![test3](https://example.com/assets/image3.png?raw=true)
But I need the result to be,
Some text ![test1](https://example.com/assets/image1.png?raw=true)
some text ![test2](https://example.com/assets/image2.png?raw=true) some other text
![test3](https://example.com/assets/image3.png?raw=true)