Skip to content

Instantly share code, notes, and snippets.

@Eyad-Bereh
Created July 4, 2019 23:00
Show Gist options
  • Save Eyad-Bereh/b5879b5cea01cca5c78fd98c6093ae01 to your computer and use it in GitHub Desktop.
Save Eyad-Bereh/b5879b5cea01cca5c78fd98c6093ae01 to your computer and use it in GitHub Desktop.
A JS function to replace links that points to images of types JPG,PNG,or JPEG into an <img> element that view them
function ConvertLinksToMultimedia(text) {
const regex = /(?<!src\=\')https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)\.(png|jpg|jpeg)(?!\')/i;
while (regex.test(text)) {
text = text.replace(regex, (match) => {
return "<img src='" + match + "'>";
});
}
return text;
}
let text = "an image can be found here: https://www.example.com/test.png , take a look and write your comment ...\nanother image is here: http://www.example.com/figure.jpeg click to see it ...\nmore info can be found here: https://www.example.com/index.html .";
console.log(ConvertLinksToMultimedia(text));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment