By the end of this page you will be able to:
Working with Strings
A string is most often text, for example "Hello World!". To stick two or more string variables together (concatenate), use the + operator
Example :Click here to run js1_06.
Prompting for numbers (js1_07)
(As this uses the prompt command will not work if downloaded from the Internet in IE 7+)
When you use the prompt (or input box) to get a user to submit a number of things can go wrong!
Example :Click here to run js1_07.
Alternative example for IE 7+ (js1_07a)
To show how this works in IE 7 we will assign the number "10" to num1 and "25" num2
Example :Click here to run js1_07a.
Converting text to numbers
- Adding "12" + "34" will give "1234" whereas
- Adding numbers 12 + 34 gives 46
When you get user input via a textbox (notice it is called a TEXT box) numbers are captured as strings, so before you can add them they need to be converted to numbers. You can force a number conversion by simply adding a number to the text value e.g.
Or you can use number conversion functions such as;
- parseFloat - for conversion to a floating-point number
- The example below will give 10.33.
- Other conversions: "12" (12), "12.00" (12), "12.25" (12.25), "31 32 33" (31), " 22" (22), "25 years" (25), "age is 25", (NaN)
- parseInt - for string-to-integer conversion.
- eval(string) - where the string is evaluated.
If you want to manage the number of decimal points use
Converting text to numbers (js1_08)
(Contains prompt will work in most browsers and IE 7+ offline)
To convert an input string to number we need to use parseInt() or parseFloat()
Example :Click here to run js1_08.