0

I have the variable below:

myvar = '<img src=".images/myimage.jpg"/>';

How can i get only the ".images/myimage.jpg" in a variable using regular expressions?

3
  • "([^"]*)" grab the string you want from index 1. Commented Mar 13, 2015 at 12:41
  • 1
    stackoverflow.com/questions/1732348/… Commented Mar 13, 2015 at 12:41
  • why with regular expression?? you can do it using a substring. I can show you how do it if you want Commented Mar 13, 2015 at 12:42

2 Answers 2

11

No need for a regex which could be problematic.

var src = $(myvar).attr('src');
Sign up to request clarification or add additional context in comments.

2 Comments

This is the correct answer. Under the hood, what happens is that the $ function parses the HTML string to build a DOM element. You then retrieve its src attribute. The main benefit of this approach is that it is guaranteed to correctly parse the HTML.
@SalmanA You're right, having the Vanilla JS option as an answer might be good for other readers
4

Using Regular Expression is not the way to go, you should instead parse the HTML.

You could use jQuery, to parse rapidly the HTML and then the src attribute. This other answer is good and you should use that if jQuery is loaded.

Nonetheless, if jQuery is not loaded, you should not load it just for that.

If you want to get the src property or attribute (they are not the same) you can create a div and insert you HTML string into it. You will then be able to traverse the DOM and get the image src.

var wrapper = document.createElement('div');
wrapper.innerHTML = '<img src=".images/myimage.jpg"/>';
var img = wrapper.querySelector('img');

console.log(img.src);
console.log(img.getAttribute('src'));

Note that this snippet assume there will always be an image in the string. There is no condition to prevent error (but are easy to do).

See it in action here.

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.