JBa
JBa

Reputation: 5509

How can I convert this into a integer in Javascript?

I asked a similar question yesterday .. If I have for example 0-9999 , how can I turn this into 09999 , basically removing the - and make it an integer in javascript ?

var = 0-9999

turn that into 9999 integer

or var = 2-9999 , turn that into 29999

Thanks a bunch

Upvotes: 0

Views: 354

Answers (4)

JHixson
JHixson

Reputation: 1522

Remember that

var x = 2-9999

is the same as

var x = -9997

because the dash is seen as a subtraction symbol unless you use quotation marks (Single or double, doesn't matter).

So, assuming that you properly quote the text, you can use the following function to always pull out a character that is in any given spot of the text (Using a zero-based index).

function extractChar(myString,locationOfChar){
    var y = myString.substring(0,locationOfChar-1)
    var z = myString.substring(locationOfChar+1)
    var s = y.concat(z)
    var i = parseInt(s,10)
    return i 
}

therefore

var i = extractChar("2-9999",1)

Will be the same as

var i = 29999

Upvotes: 0

Mike Christensen
Mike Christensen

Reputation: 91608

Try this:

var i = '0-9999';
var int = Number(i.replace('-', ''));
window.alert(int);

Note in Firefox, parseInt() won't work with leading zeros unless you pass in a radix (this appears to be a bug):

var int = parseInt(i.replace('-', ''), 10);

Fiddler

Upvotes: 1

Lloyd
Lloyd

Reputation: 29668

The most obvious and basic of solutions would be:

var s = "1-2345";
var t = s.replace("-","");
var i = parseInt(t,10);

But that's making a lot of assumptions and ignoring any errors.

Upvotes: 4

Elliot Bonneville
Elliot Bonneville

Reputation: 53301

This should do the trick:

num = num.replace(/[^0-9]+/g, '') * 1;

It'll strip out any non-numeric characters and convert the variable into an integer. Here's a jsFiddle demonstration for you.

Upvotes: 5

Related Questions