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

  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 );

Solution 3

You can replace all white space with replace function

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

OutPut is 120000

Share:
13,168

Related videos on Youtube

passion
Author by

passion

Updated on October 17, 2022

Comments

  • passion
    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? 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.

  • passion
    passion about 7 years
    i updated my question, i currently have problem integrating your response.
  • passion
    passion about 7 years
    i updated my question, i can't succeed applying your solution
  • Abhinav Galodha
    Abhinav Galodha about 7 years
    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.
  • passion
    passion about 7 years
    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?
  • Mike Cluck
    Mike Cluck about 7 years
    @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.
  • Abhinav Galodha
    Abhinav Galodha about 7 years
    which string value is it failing? this solution should work for any numbers