javascript parseInt to remove spaces from a string
13,168
Solution 1
You can remove all of the spaces from a string with replace
before processing it.
var input = '12 000';
// Replace all spaces with an empty string
var processed = input.replace(/ /g, '');
var output = parseInt(processed, 10);
console.log(output);
Solution 2
- Remove all whitespaces inside string by a replace function.
- using the
+
operator convert the string to number.
var mynumber = Number.MIN_SAFE_INTEGER;
mynumber = "120 000";
mynumber = mynumber.replace(" ", "");
console.log(+mynumber );
Solution 3
You can replace all white space with replace function
var mynumber = "120 000";
console.log(mynumber.replace(/ /g,''));
OutPut is 120000
Related videos on Youtube
Author by
passion
Updated on October 17, 2022Comments
-
passion over 1 year
I have an example of data that has spaces between the numbers, however I want to return the whole number without the spaces:
mynumber = parseInt("120 000", 10); console.log(mynumber); // 120
i want it to return
120000
. Could somebody help me with this? thanksupdate
the problem is I have declared my variable like this in the beginning of the code:
var mynumber = Number.MIN_SAFE_INTEGER;
apparently this is causing a problem with your solutions provided.
-
passion about 7 yearsi updated my question, i currently have problem integrating your response.
-
passion about 7 yearsi updated my question, i can't succeed applying your solution
-
Abhinav Galodha about 7 yearsThe
Number.MIN_SAFE_INTEGER
constant represents the minimum safe integer in JavaScript. If your myNumber is assigned that value, then why are you converting it again to number ? In case, you are overriding the value from number to a string, then also it should work. I updated the answer as per your comment. -
passion about 7 yearsthe problem is that not all of the instances of
mynumber
has space, so this solution breaks when there is not. what should i do then? -
Mike Cluck about 7 years@marcel Assigning
Number.MIN_SAFE_INTEGER
to it will not cause any problems. You're just re-assigningmynumber
to a different value, presumably. Please create a [minimal, complete and verifiable example](stackoverflow.com/help/mcve) of your problem and I'd be more than happy to help you solve it. If you need something to help you quickly hash it out, JSFiddle is great for that sort of thing. -
Abhinav Galodha about 7 yearswhich string value is it failing? this solution should work for any numbers