How can I do the following in JavaScript?
Concatenate "1", "2", "3" into "123"
Convert "123" into 123
Add 123 + 100 = 223
Covert 223 into "223"
Adding empty string to the number value will convert the data to string is one of the simplest way to do the job. It is also considered to be faster than the above two when it comes to performance.
In JavaScript, a built-in method isNaN() evaluates the string in such a way that if the passed string is a number. This built-in function of JavaScript returns a true or false output based on the passing string. Furthermore, the “+” operator is employed to check the string by converting the string into a number.
To convert a string to an integer parseInt() function is used in javascript. parseInt() function returns Nan( not a number) when the string doesn't contain number. If a string with a number is sent then only that number will be returned as the output. This function won't accept spaces.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With