0

I have a string like follows in javascript

var str='<img class="avatar  avatar-small 012345" src="/img/staff_avatar_profile.jpg" />&nbsp; 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

Charaf JRA
  • 8,249
  • 1
  • 34
  • 44
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

4 Answers4

2

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/

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
0

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/

CharliePrynn
  • 3,034
  • 5
  • 40
  • 68
0

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.

Community
  • 1
  • 1
0

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" />
Valentin S.
  • 504
  • 2
  • 10