2

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:

  • Form 1: "/site/images/test.png"
  • Form 2: "/site/images/test.png?size=3"
  • Form 3: "<img src='/site/images/test.png />"
  • Form 4: "<img src='/site/images/test.png?size=3' />"
  • Form 4: "<div><img src='/site/images/test.png?size=3' /></div>"
  • Form 5: "" return empty string

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

1
  • Just to be clear, you need the fullpath or just the filename ? Commented Apr 19, 2015 at 19:25

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.