jobin
jobin

Reputation: 1139

extract image path using javascript regex

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:

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

Answers (3)

uraimo
uraimo

Reputation: 19791

This is the regex you should use:

.*?(\/[\/\w\.]+)[\s\?]?.*

See it in action on regex101.

enter image description here

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

Federico Piazza
Federico Piazza

Reputation: 30985

You can use a simple regex like this:

(\/.*\.\w+)

Working demo

enter image description here

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

Pedro Lobito
Pedro Lobito

Reputation: 98861

Try this regex, will match all the images:

/(\/.*?\.\w{3})/img

REGEX DEMO


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

CODEPEN DEMO

Upvotes: 0

Related Questions