Reputation: 16651
I have a string like follows in javascript
var str='<img class="avatar avatar-small 012345" src="/img/staff_avatar_profile.jpg" /> olah blah';
I need to get every time the number like for this example 012345. Which will be ofcourse be different in different scenario and I also need to get the text olah blah which will be also different in different scenario.
I have the above string in a variable. ;)
How can i perform this in a efficient manner in java-script
Upvotes: 0
Views: 115
Reputation: 219930
The best way to parse HTML in a browser is to let the browser do it for you:
var div = document.createElement('div');
div.innerHTML = str;
var numbers = div.getElementsByTagName('img')[0].className.match(/ (\d+)/)[1];
Here's the fiddle: http://jsfiddle.net/CGuLC/1/
Upvotes: 2
Reputation: 504
If you need to store data for an element, one good way to achieve that is to use the data-key attribute with jQuery:
$('.avatar').data('number', '012345'); // set value
var number = $('.avatar').data('number'); // get value
The rendered markup will look like this:
<img class="avatar avatar-small" data-number="012345" src="/img/staff_avatar_profile.jpg" />
Upvotes: 0
Reputation: 720
You could use jQuery if it works there to get an only numeric class name. Take a look at jQuery - selectors on a html string to get a clue.
Upvotes: 0
Reputation: 3082
Use the data attribute instead of class.
<img class="avatar avatar-small" data-id="012345" src="/img/staff_avatar_profile.jpg" />
Then use jQuery to get the data attribute.
jQuery('.avatar').data('id');
Sources: http://html5doctor.com/html5-custom-data-attributes/ http://api.jquery.com/data/
Upvotes: 0