JavaScript: Strings II

 

Number <--> String Conversions

JavaScript provides different ways of converting between numbers and strings. One way of converting from a string to an integer is with the 'parseInt()' function. The 'parseFloat()' function converts from a string to a real number. The 'Number()' function also converts a string to a number. Examples that use 'parseInt()' and 'Number()' are given below.

To go the other way, converting a number to a string, the 'String()' function can be used. For example:

someString = String(someNumber)

converts the number 'someNumber' to the string 'someString'.

Another tool for converting a number to a string is the 'toString()' method. For example:

someString2 = someNumber2.toString()

converts the number 'someNumber2' to the string 'someString2'.

The 'parseInt()' and 'toString()' functions allow the programmer to do conversions from one base to a different base while also converting between strings and numbers. For example:

res = i.toString(2)

converts the number 'i' to base 2 and saves the result as the string variable 'res'.


Example 1

Let's do an example that involves converting from a string to a number. Here we have built a simple calculator which allows us to add numbers to "1985". The value "1985" is stored as a string. Here is the script for the first example:

<script language=JavaScript>
<!--
function doIt(form)
{
form.result.value=form.first.value + form.toAdd.value
}
//-->
</script>
</HEAD>
<BODY>
<center>
<table>
<form>
<tr>
<td colspan=2><input type=text size=4 name=first value="1985">
<tr>
<td><input type=text size=3 value="+"><td> 
<tr>
<td><input type=text name=toAdd onChange="doIt(this.form)">
<td>(enter value)
<tr>
<td>----------------------
<tr>
<td><input type=text name=result ><td>(click anywhere)
</form>
</table>

to see this how this script behaves in a new window.

 

Example 2

The result in Example 1 is probably not what we have in mind for this calculator. To do the addition of "1985" and whatever number the user enters in the blank box, we can convert both strings to numbers before we add.

Let's revise the function in the script above to use the 'Number()' function:

function doIt(form)
{
form.result.value=Number(form.first.value) + Number(form.toAdd.value)
}

to see this how this script behaves in a new window.

 

Example 3

The use of the 'Number()' function in Example 2 provides what we had in mind for the calculator. Here is another version of the 'doIt()' function -- using 'parseInt()' -- that should work:

function doIt(form)
{
form.result.value=parseInt(form.first.value) + parseInt(form.toAdd.value)
}

to see this how this script behaves in a new window.

 
Adding Strings Together

Let's do an example in which we create a string by adding together 2 other strings. We set up 3 text boxes. In the first text box we ask the user to enter 4 characters. In the second box we ask the user for the year of his/her birth. We then use an 'onChange' event-handler inside the 'input' tag that creates the second box. The 'onChange' event-handler creates a password in the third box that is built from the strings entered into the first 2 boxes. Here is the script:

<BODY>
<table width=100%>
<form>
<tr>
<td>Enter four characters:<td><input type=text maxlength=4 name=yourName value="">
<tr>
<td>Enter the year you were born:<td><input type=text maxlength=4 name=yearOfBirth value="" onChange="password.value=yourName.value + yearOfBirth.value">
<tr>
<td>Click anywhere to create your password:<td><input type=text value="" name=password>
<tr>
<td colspan=2><hr></td>
<tr>
<td colspan=2> </td>
<tr>
<td><input type=button value="Calculate your age:" ><td><input type=text name=age value="">
</form>
</table>

to see this how this script behaves in a new window.

You write some script to activate the 'Calculate Your Age' button in the Exercise below.

 
Other Resources

Try this link on forms and functions


Page Link
Passing Information to a Function (JavaScript Goodies) www.htmlgoodies.com/primers/jsp/article.php/3478311

or check out one of our reference books, or look for other help on the Web.

 

Exercise

You will want to get a copy of the entire script that created the example above in the 'Adding Strings Together' section. Here is a link to the script. (Choose 'View Source' and copy the script into a blank page.)

Modify the script so that the button 'Calculate your age' works. Modify the 'input type=button' tag so that the 'calculateAge' function is called when the button is clicked. Send 'this.form' to the function inside the parentheses.

Write the function 'calculateAge(form)'. Extract the user's year of birth from the 8-character password. Use the 'substr()' method to do this. The method 'substr()' starts at a given point in a string and extracts a given number of characters. For example:

name = "BillClinton".substr(4,7)

begins at the 4th character of "BillClinton" and extracts 7 characters. The result is that 'Clinton' is stored in the variable 'name'. (The 4th character is 'C' because the numbering starts at 0.)

Next in 'calculateAge()' use a 'prompt' to ask the user whether or not his/her birthday has occurred yet this year. The message in the 'prompt' could look like:

Has your birthday occurred yet this year (y/n) ?

Then write an IF statement (using the result of the 'prompt') in which you calculate the user's age.

Finally, store the user's age in the text box named 'age'.