user208709
user208709

Reputation: 475

Convert complicates string into integer?

I've retrieved a string into a variable with innerHTML method. The string is:

£ 125.00
<!-- End: pagecomponent/pricesplit -->

I only want the 125.00 part. Is it possible to use the parseInt() method to convert this into an integer? Alternatively what can I do to extract the 125.00 part?

Thanks

Upvotes: 0

Views: 428

Answers (2)

Minko Gechev
Minko Gechev

Reputation: 25672

You can get the value using regular expression. Here is an example:

var str = '£&nbsp;125.00<!-- End: pagecomponent/pricesplit -->';
parseInt((/\d+/).exec(str)[0], 10);

Or if you also want to get the zeroes:

(/\d+\.\d+|\d+/g).exec(str)[0]

You can't get it directly using parseInt because when a string does not start with number parseInt does not work.

Upvotes: 1

jbabey
jbabey

Reputation: 46647

You probably want to use a regular expression to remove anything but digits and periods, and then run parseInt on the remaining string:

parseInt(yourString.replace(/[^\d.]/g, ''), 10);

Test the regex here. Here's a breakdown:

/.../ is just the syntax you use for wrapping a regular expression. Ignore these.

[...] creates a character class.

^ when placed at the beginning of a character class, it negates everything inside.

\d any digits

. a literal period. It does not need to be escaped inside a character class - outside it would mean "any character" and need to be escaped.

So /[^\d.]/ means "match anything that is not a digit or period", and subsequently replace it with an empty string.

If your number might include significant digits after the decimal, such as 125.50, you should use parseFloat instead of parseInt.

Upvotes: 3

Related Questions