damien
damien

Reputation: 171

jquery find integer inside string

My text:

var str = 'Cost USD 400.00';

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

Upvotes: 3

Views: 3820

Answers (3)

Reinderien
Reinderien

Reputation: 15231

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 .

Upvotes: 6

Alex C
Alex C

Reputation: 17004

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.

Upvotes: 0

gillyb
gillyb

Reputation: 8910

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

Upvotes: -1

Related Questions