0

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

1
  • 2
    Do you have it as strings? I mean, var x = "2-9999"? Because var x = 2-9999 is -9997. Commented Feb 1, 2013 at 20:50

4 Answers 4

5

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.

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

3 Comments

Shorter: num = +num.replace(/\D/g, '')
@gilly3: Clever. :) I like the +num method, but *1 was the first that came to mind.
@gilly3 I think you give up too much readability, though I like the shorter regex. It's more obvious IMO what * 1 is doing vs + prefix.
4

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.

11 Comments

@ElliotBonneville He's only supplied dashes, but you are right. Like your solution, +1!
parseInt will convert 09999 into 0.
@MikeChristensen Really? Not 9999?
Don't forget your radix. :)
It depends on the browser, but older ones will assume base 8 and return NaN or 0 for 09999. The safe route is parseInt(t, 10).
|
1

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

1 Comment

There is a bug report indeed: bugzilla.mozilla.org/show_bug.cgi?id=510415
0

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

Comments

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.