Văn Đức Nguyễn
Văn Đức Nguyễn

Reputation: 54

Regular Expression: Only convert url "http|https" outside element

I have a string:

http://localhost/xyz
http://localhost/rpq
http://localhost/abc
<img src="http://localhost/xyz/image.png">

Now, I want to convert only:

http://localhost/xyz
http://localhost/rpq
http://localhost/abc

to link url, but not convert <img src="http://localhost/xyz/image.png"> to link url. Can you help me this problem with regular expression, please. Thank you so much.

Upvotes: 0

Views: 123

Answers (2)

Ritesh Khandekar
Ritesh Khandekar

Reputation: 4005

This can be done by DOMParser():

var text = `<img src="http://localhost/xyz/image.png">`;
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(text, 'text/html');
console.log(htmlDoc.querySelector("img").src);
var text = `http://localhost/xyz
http://localhost/rpq
http://localhost/abc
<img src="http://localhost/xyz/image.png">`;
console.log(text.split("\n").map(function (v){return v.match(/^http/) ? v : getimgsrc(v);}).join("\n"));
function getimgsrc(text){
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(text, 'text/html');
return htmlDoc.querySelector("img").src;
}

Upvotes: 0

Ken Yip
Ken Yip

Reputation: 761

You can use ^ to specify http/ https in the start of the sentence. For example:

^(?:http|https)\:\/\/.+

Upvotes: 1

Related Questions