0

I'm trying to get the initial number value of a string using jQuery/Javascript. Right now, the string I'm getting is:

  2 <a href="user/[email protected] ">view</a>

I'm trying to take this string (which is stored in a variable, and take only the initial number from it. Normally, I would take only the first digit, but I'm want to make this flexible, so the number could be any digits in length (for example, "2" to "20,000,000"), so I know that just taking the first few digits doesn't work.

Does anyone out there have a solution? Thank you for your time!

2
  • Could you please rephrase your question, it's pretty hard to understand. Commented Oct 12, 2012 at 13:52
  • "20,000,000" including the commas? Commented Oct 12, 2012 at 13:57

6 Answers 6

1
var str = '2 <a href="user/[email protected] ">view</a>​​​​​​​​​​​​​';
var parts = str.split(' ');
alert(parts[0]);​​​​
Sign up to request clarification or add additional context in comments.

Comments

1

Use parseFloat. It'll stop when it meets an non numeric character.

parseFloat(mystring);

Comments

0

One of the solutions is using regex ^\d+ if you want to grab just digits, or ^[\d,]+ if you allow commas:

var input = '2 <a href="user/[email protected] ">view</a>';
var number = input.match(/^\d+/g);

Comments

0
function getNum ( str ) {
    var result = '';
    var nums = str.match(/^(\d+|\,)*/);
    if(nums[0])
        result = parseFloat(nums[0].replace(/,/g,''));

    return result;
}

Usage:

getNum ('2 <a href="user/[email protected] ">view</a>')
Ouput: 2

getNum ('20,000,000 <a href="user/[email protected] ">view</a>')
Output: 20000000

Comments

0

If the number isn't comma-delimited:

var s   = '1234 <a href="user/[email protected] ">view</a>',
    num = parseInt(s, 10);

If the number is comma-delimited:

var s   = '1,234 <a href="user/[email protected] ">view</a>',
    num = parseInt(s.match(/^\d{1,3}(?:,\d{3})*/)[0].replace(/,/g, ''), 10);

Comments

0

If there could be commas in the number, and maybe a dot for decimals, and there is always a space afterwards, I would match using a regex like this...

var str = '2,000.33 <a href="user/[email protected] ">view</a>'
var bits = str.match(/^[\d,\.]+/)

// alerts 2,000.33
alert(bits[0])

// to convert to string...
num = parseFloat(bits[0].replace(/,/g,''))

alert(num)
// alerts: 2000.33 (treated as number, not as string representation of number)

1 Comment

parseInt('2,000.33') is equal to 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.