admin管理员组

文章数量:1317898

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?

Share Improve this question asked Mar 13, 2015 at 12:40 vaspantvaspant 653 silver badges11 bronze badges 3
  • "([^"]*)" grab the string you want from index 1. – Avinash Raj Commented Mar 13, 2015 at 12:41
  • 1 stackoverflow./questions/1732348/… – Luizgrs 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 – gon250 Commented Mar 13, 2015 at 12:42
Add a ment  | 

2 Answers 2

Reset to default 11

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

See it in action here.

本文标签: jqueryJavascript regular expressions Getting the image srcStack Overflow