user2613399
user2613399

Reputation: 785

Extracting a specific number from a string

I have an element in javascript like follows:

var count1 = '<span data-modelName="count[0]"> 3 </span>';
var count2 = '<span data-modelName="count">3</span>';

I want to extract 3 from the span element. How can i do it? The content within span element will be any number of digits.

Upvotes: 1

Views: 51

Answers (2)

Ben Pearce
Ben Pearce

Reputation: 7094

It's super easy if you're using jQuery.

var selector = $('<span data-modelName="count[0]"> 3 </span>');
var three = selector.html();

If you want to have it formatted as an integer (i.e. do math on it), it's one extra step

three = parseInt(three);

fiddle

Upvotes: 1

Ganesh Jadhav
Ganesh Jadhav

Reputation: 2848

If you want pure javascript:

var integer = parseInt(count1.substr(count1.indexOf('>') + 1, count1.indexOf('</') - count1.indexOf('>') - 1));

Here is the fiddle: http://jsfiddle.net/V4q4t/

Upvotes: 1

Related Questions