javascript parseInt to remove spaces from a string
Asked Answered
M

4

10

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? thanks

update

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.

Marcela answered 18/1, 2017 at 21:20 Comment(2)
Did you mean to type parseInt('120 000', 10)?Mudd
@MikeC yes i updated it, sorry.Marcela
M
13

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);
Mudd answered 18/1, 2017 at 21:22 Comment(2)
i updated my question, i currently have problem integrating your response.Marcela
@marcel Assigning Number.MIN_SAFE_INTEGER to it will not cause any problems. You're just re-assigning mynumber 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.Mudd
D
2
  1. Remove all whitespaces inside string by a replace function.
  2. using the + operator convert the string to number.

var mynumber = Number.MIN_SAFE_INTEGER;
mynumber = "120 000";
mynumber = mynumber.replace(" ", ""); 
console.log(+mynumber );
Digiacomo answered 18/1, 2017 at 21:23 Comment(4)
i updated my question, i can't succeed applying your solutionMarcela
The 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.Digiacomo
the 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?Marcela
which string value is it failing? this solution should work for any numbersDigiacomo
P
1

You can replace all white space with replace function

var mynumber = "120 000";
console.log(mynumber.replace(/ /g,''));

OutPut is 120000

Pastorship answered 18/1, 2017 at 21:28 Comment(0)
M
0

Just like playing with javascript :-)

var number= '120 00'; 
var s= '';
number = parseInt(number.split(' ').join(s), 10);
alert(number);
Milestone answered 18/1, 2017 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.