Click to See Complete Forum and Search --> : Finding the first number in a string.


AntonioMainenti
01-25-2003, 08:55 AM
I'm wondering if there's some sort of built-in function that finds the first number in a string. For example, I would want 'var2_w5' to return 2. I tried parseInt and parseFloat, which I don't know much about, but they both returned 'NaN'.

Or would I have to do a loop that goes through the string until it finds a number?

Thanks, Alan.

khalidali63
01-25-2003, 09:14 AM
JavaScript does not have any buil in methods that will strip a or any number from a string for you.
You will have to parse throught the string and find the first or Nth number.
you can use charAt(n)
and see if its the first instance of number then break the loop

Khalid

Charles
01-25-2003, 12:00 PM
<script type="text/javascript">
<!--
String.prototype.firstNumber = function () {return this.match(/\d+\.?\d*/)}

alert ('var2_w5'.firstNumber())
// -->
</script>