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?

vaspant
  • 65
  • 3
  • 11

2 Answers2

11

No need for a regex which could be problematic.

var src = $(myvar).attr('src');
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 1
    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. – Erik Schierboom Mar 13 '15 at 12:43
  • 1
    @SalmanA You're right, having the Vanilla JS option as an answer might be good for other readers – Karl-André Gagnon Mar 13 '15 at 13:13
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.

Community
  • 1
  • 1
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75