tags:

views:

65

answers:

3

Hi,

My text:

var str = 'Cost USD 400.00';

How do i use jquery to find number only in that str?

+3  A: 

You probably shouldn't use JQuery for that; you should use built-in Javascript regular expression support. In this case your regular expression might look like:

var result = /\d+(?:\.\d+)?/.exec(mystring);

The official reference for this is at https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/RegExp .

Reinderien
you may wish to follow that with parseFloat() to turn into a number
second
Your solution doesn't work: http://jsfiddle.net/3LmHH/
patrick dw
Change "\\" to "\". But it is returning any number, not an integer. Is it really what the OP want?
BrunoLM
A: 

Just search for the number using a plain RegEx object in javascript. No need for jquery here.

e.g :

var str = new RegExp("\\d+(?:\\.\\d+)");
var num = str.exec("Cost USD 400.00");
gillyb
The 'test' method would return true if there is a number, but wouldn't actually give you the number back. In addition, you wouldn't get the ".00" from this regex.
Reinderien
I immidiatly realized i posted the start method instead of .exec, so i changed it. About the regular expression, I meant to add on to your (@Reinderien) answer, and just wanted to give damien the code he could actually use, because it seems like he doesn't know how to, and that was before you edited your answer.
gillyb
A: 

What gillyb said but I'd just add:

var str=new RegExp("\\d+\.?\d+?");

To pick up anything after the decimal point.

The above RegEx should match

400

400.01

400.0

400.001

I often use http://xenon.stanford.edu/~xusch/regexp/analyzer.html when building regular expressions... but you also might find this one very useful http://www.regular-expressions.info/javascriptexample.html

if you put the regex on line one, the string your testing against on line 2 then you can see what gets put into the variable with the SHOW MATCH button.

Try it with variations of the above numbers and see what comes back.

Alex C