Reputation: 1139
I request information form web service using ajax and this service return image for me and I need to use the image in my code.
my issue with this service, it is return difference of text:
<img src='/site/images/test.png />
"<img src='/site/images/test.png?size=3' />
"<div><img src='/site/images/test.png?size=3' /></div>
"this service bring data from legacy system and based on the users input that time, I cant change the service. I need way to extract the image path using JavaScript. this path should be the image path only without any tags or query strings.
Note: the Images extension will be any type
Upvotes: 2
Views: 3648
Reputation: 19791
This is the regex you should use:
.*?(\/[\/\w\.]+)[\s\?]?.*
See it in action on regex101.
How to use it in Javascript:
var rex = /.*?(\/[\/\w\.]+)[\s\?]?.*/;
var res = rex.exec("<img src='/site/images/test.png?size=3' />");
console.log(res[1]); //Will print /site/images/test.png
Link to JSFiddle.
Upvotes: 1
Reputation: 30985
You can use a simple regex like this:
(\/.*\.\w+)
Javascript code
var re = /(\/.*\.\w+)/g;
var str = 'Form 1: "/site/images/test.png"\nForm 2: "/site/images/test.png?size=3"\nForm 3: "<img src=\'/site/images/test.png />"\nForm 4: "<img src=\'/site/images/test.png?size=3\' />"\nForm 4: "<div><img src=\'/site/images/test.png?size=3\' /></div>"\nForm 5: "" return empty string';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Upvotes: 0
Reputation: 98861
Try this regex, will match all the images:
/(\/.*?\.\w{3})/img
Your code may look like this:
var image = "<div><img src='/site/images/test.png?size=3' /></div>";
result = image.match(/(\/.*?\.\w{3})/img);
console.log(result[0]);
Output:
/site/images/test.png
Upvotes: 0