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
2 Answers
Reset to default 11No 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
版权声明:本文标题:jquery - Javascript regular expressions. Getting the image src - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742035004a2417181.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论