3

My text:

var str = 'Cost USD 400.00';

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

1
  • From this example are you expecting null? There are no integers there, just a float Commented Jul 22, 2010 at 17:21

3 Answers 3

6

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 .

Sign up to request clarification or add additional context in comments.

2 Comments

you may wish to follow that with parseFloat() to turn into a number
Change "\\" to "\". But it is returning any number, not an integer. Is it really what the OP want?
0

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.

Comments

-1

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");

2 Comments

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.
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.

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.