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?
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?
No need for a regex which could be problematic.
var src = $(myvar).attr('src');
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).