91

How can I do the following in JavaScript?

  1. Concatenate "1", "2", "3" into "123"

  2. Convert "123" into 123

  3. Add 123 + 100 = 223

  4. Covert 223 into "223"

Undo
  • 25,519
  • 37
  • 106
  • 129
user366312
  • 16,949
  • 65
  • 235
  • 452
  • 43
    Almost all JavaScript books I have read deal with these issues. But that's OK. Answering questions is what StackOverflow is all about. @Shadi Almosri--SO has a "don't be mean" rule. I don't see the point of belittling people who ask questions here, since that's the point of the place. – Nosredna Jun 09 '09 at 16:28
  • 4
    @Nosredna: i completely understand asking questions, i love nothing more than answering them, but i think showing the fact that you've tried is better etiquette then simply expecting an answer and also better for a personal experience of learning. Just my opinion, not trying to be mean! :) – Shadi Almosri Jun 09 '09 at 16:31
  • 1
    @Shadi, so how should the question have been asked? With a declaration of having looked for the answer already? – Nosredna Jun 09 '09 at 16:34
  • 1
    It struck me as sort of homeworky when I first saw it, but as I reread it I thought not, it seemed like someone experimenting in JavaScript and getting unexpected results and wanting to nail it down. That said, I wonder if the http://stackoverflow.com/faq might include something like an honor code for students. We're sort of a global university here, and I don't think it's crazy to try to figure out what a set of ethics might be for this place. Or maybe it is crazy. :-) – artlung Jun 09 '09 at 16:36
  • @nosredna Showing example code of an attempt is enough to get me trying all i can to help. I mean come on http://www.google.co.uk/search?q=javascript+convert+string+int how hard is that to search for? He even had the hard part with the first step by knowing the technical term: http://www.google.co.uk/search?q=Concatenate+javascript maybe? All simple processes thus an attempt at this would imo been more helpful overall The way the question was asked showed lazy rather than "stuck". again just my own opinion. I clearly care about helping or i wouldn't have wasted so much time commenting here! – Shadi Almosri Jun 09 '09 at 17:17
  • 6
    @Shadi, well, on the positive side, the question and answer are in StackOverflow, and hopefully will help other people. I see people get stuck on this stuff all the time, especially when coming from languages like Java. There's a reason people ask this over and over--it's because they THINK they know how expressions in JavaScript work, but they don't. They make assumptions based on experience outside JS. That's why it's so useful to sit down a try a few simple tests with adding strings and numbers, and trying unary plus and minus. – Nosredna Jun 09 '09 at 17:24

10 Answers10

124

You want to become familiar with parseInt() and toString().

And useful in your toolkit will be to look at a variable to find out what type it is—typeof:

<script type="text/javascript">
    /**
     * print out the value and the type of the variable passed in
     */

    function printWithType(val) {
        document.write('<pre>');
        document.write(val);
        document.write(' ');
        document.writeln(typeof val);
        document.write('</pre>');
    }

    var a = "1", b = "2", c = "3", result;

    // Step (1) Concatenate "1", "2", "3" into "123"
    // - concatenation operator is just "+", as long
    //   as all the items are strings, this works
    result = a + b + c;
    printWithType(result); //123 string

    // - If they were not strings you could do
    result = a.toString() + b.toString() + c.toString();
    printWithType(result); // 123 string

    // Step (2) Convert "123" into 123
    result = parseInt(result,10);
    printWithType(result); // 123 number

    // Step (3) Add 123 + 100 = 223
    result = result + 100;
    printWithType(result); // 223 number

    // Step (4) Convert 223 into "223"
    result = result.toString(); //
    printWithType(result); // 223 string

    // If you concatenate a number with a 
    // blank string, you get a string    
    result = result + "";
    printWithType(result); //223 string
</script>
RamenChef
  • 5,557
  • 11
  • 31
  • 43
artlung
  • 33,305
  • 16
  • 69
  • 121
  • Any particular reason you put this in script tags? – Julix Nov 02 '16 at 04:52
  • 1
    @Julix For novices in 2009, plopping into an html file to learn a basic concept. If I were answering this fresh today I might do it differently, but maybe not. – artlung Nov 04 '16 at 19:20
55

Step (1) Concatenate "1", "2", "3" into "123"

 "1" + "2" + "3"

or

 ["1", "2", "3"].join("")

The join method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string ("").


Step (2) Convert "123" into 123

 parseInt("123")

Prior to ECMAScript 5, it was necessary to pass the radix for base 10: parseInt("123", 10)


Step (3) Add 123 + 100 = 223

 123 + 100

Step (4) Covert 223 into "223"

 (223).toString() 

or

 String(223)

Put It All Togther

 (parseInt("1" + "2" + "3") + 100).toString()

or

 (parseInt(["1", "2", "3"].join("")) + 100).toString()
Patrick McElhaney
  • 57,901
  • 40
  • 134
  • 167
  • 4
    Nice, clear example. Also, kudos for good form--you should always [specify the radix for the `parseInt` function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt). – hotshot309 Jan 03 '12 at 16:50
  • Including the radix confused me and I scrolled on to another answer where it was explained. Edited in a quick explanation to be right at the point of confusion. – ArtOfWarfare Dec 30 '17 at 14:59
  • @ArtOfWarfare Thanks, good edit. The radix was necessary at the time of this answer. These days, an argument can me made to leave it out. As of ES5, which all “modern” browsers and Node.js support, parseInt() always uses base 10. – Patrick McElhaney Dec 30 '17 at 15:14
  • fun fact.. in Netscape's original JavaScript (circa 1995) the default radix for parseInt was 8 (unless the string contained and 8 or a 9) – Justin Ohms Apr 13 '18 at 15:07
27
r = ("1"+"2"+"3")           // step1 | build string ==> "123"
r = +r                      // step2 | to number    ==> 123
r = r+100                   // step3 | +100         ==> 223
r = ""+r                    // step4 | to string    ==> "223"

//in one line
r = ""+(+("1"+"2"+"3")+100);
cesarl
  • 373
  • 4
  • 5
  • If you check it is a number or not then use parseInt(). For example, parseInt(" ") is NaN, but +" " is 0! – greene May 25 '17 at 19:29
15

These questions come up all the time due to JavaScript's typing system. People think they are getting a number when they're getting the string of a number.

Here are some things you might see that take advantage of the way JavaScript deals with strings and numbers. Personally, I wish JavaScript had used some symbol other than + for string concatenation.

Step (1) Concatenate "1", "2", "3" into "123"

result = "1" + "2" + "3";

Step (2) Convert "123" into 123

result = +"123";

Step (3) Add 123 + 100 = 223

result = 123 + 100;

Step (4) Convert 223 into "223"

result = "" + 223;

If you know WHY these work, you're less likely to get into trouble with JavaScript expressions.

Benoit Garret
  • 14,027
  • 4
  • 59
  • 64
Nosredna
  • 83,000
  • 15
  • 95
  • 122
  • 3
    I actually think this is extremely bad practice because it's fairly opaque as to waht's going on. Knowing that certain operations affect an implicit cast is a trick, and a good one to know, but it's not at all readable. Communication is everything. – annakata Jun 09 '09 at 16:28
  • 1
    I think it's important to know these things PRECISELY so you know what's going on when you read code. Much JavaScript is terse because it's transmitted as source, and small code can mean server cost reduction. – Nosredna Jun 09 '09 at 16:30
  • 6
    You should be achieving this through compression tools though, in this form it's optimisation at a very real cost of maintenance. – annakata Jun 09 '09 at 16:37
  • 6
    Still, knowing these things would help prevent the question in the first place, which was a lack of knowledge on how JavaScript deals with strings and numbers. It's a matter of intellectual curiosity. What happens when I add a number to a string? How does unary plus work? If you don't know the answers, you don't really know JavaScript, and these kind of questions will come up. – Nosredna Jun 09 '09 at 17:15
11

You can do it like this:

// step 1 
var one = "1" + "2" + "3"; // string value "123"

// step 2
var two = parseInt(one); // integer value 123

// step 3
var three = 123 + 100; // integer value 223

// step 4
var four = three.toString(); // string value "223"
antichris
  • 2,827
  • 1
  • 22
  • 18
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • 16
    Best practice would be to add the radix parameter to the parseInt() function. so, parseInt(one, 10) assures that whatever you throw at it won't get misconverted. – artlung Jun 09 '09 at 16:23
  • 3
    Agreed. Otherwise, values starting with `0` will be seen as [octal (base-8)](http://www.electronics-tutorials.ws/binary/bin_4.html) numbers. – hotshot309 Jan 03 '12 at 17:04
  • 1
    Even more unexpected, values starting with `0` and then containing `8` or `9` will fail, leading to a return of 0. E.g., `parseInt('034') = 28`, and `parseInt('09') = 0`. – Robert Martin Sep 27 '12 at 20:23
9

To convert a string to a number, subtract 0. To convert a number to a string, add "" (the empty string).

5 + 1 will give you 6

(5 + "") + 1 will give you "51"

("5" - 0) + 1 will give you 6

Robert L
  • 1,963
  • 2
  • 13
  • 11
  • 1
    Relying on tricks based on language quirks like this can lead to real obscurity. eg "5"-0 does indeed result in the number 5, but "5"+0 results in the string "50". (Yes I know it's many years later and it's probably a bit sad I was even reading this.) – Nick Rice Jul 19 '17 at 18:53
6

parseInt is misfeatured like scanf:

parseInt("12 monkeys", 10) is a number with value '12'
+"12 monkeys"              is a number with value 'NaN'
Number("12 monkeys")       is a number with value 'NaN'
xander
  • 159
  • 2
  • 5
1

Below is a very irritating example of how JavaScript can get you into trouble:

If you just try to use parseInt() to convert to number and then add another number to the result it will concatenate two strings.

However, you can solve the problem by placing the sum expression in parentheses as shown in the example below.

Result: Their age sum is: 98; Their age sum is NOT: 5048

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

var myFather = new Person("John", "Doe", "50", "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

document.getElementById("demo").innerHTML = "Their age sum is: "+
 (parseInt(myFather.age)+myMother.age)+"; Their age sum is NOT: " +
 parseInt(myFather.age)+myMother.age; 
</script>

</body>
</html>
Joseph Callaars
  • 1,770
  • 1
  • 19
  • 28
jpsousa
  • 11
  • 1
0

Simplest is when you want to make a integer a string do

var a,b, c;
a = 1;
b = a.toString(); // This will give you string

Now, from the variable b which is of type string we can get the integer

c = b *1; //This will give you integer value of number :-)

If you want to check above is a number. If you are not sure if b contains integer then you can use

if(isNaN(c*1)) {
  //NOt a number
}
else //number
Kshitiz
  • 2,673
  • 1
  • 18
  • 24
0

We can do this by using unary plus operator to convert them to numbers first and simply add. see below:-

var a = "4";
var b = "7";
var sum = +a + +b; 
Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
singhkumarhemant
  • 177
  • 2
  • 11