A few text properties
Here are a few of the text properties
which we use in this function. There are properties for every type of object on your page. After you are through with this tutorial, you will be able to look up other properties from Netscape's Reference Page and understand how to use them.
You can extract information about a piece of text by referring to one of that variable's properties
.
The length
property tells me how many characters long a text string is. If I want to display an alert box
with how many letters I typed, I would type alert(text.length)
function DisplayLength() {
MyText = prompt("Type some text", "")
alert(MyText.length)
}
If I wanted to find the first character of a piece of text I would use the substring property. Unlike length
, the substring property needs additional information in parentheses, specifically how many places in to start and stop. Remember to always subtract 1 from how many characters places you want, because JavaScript begins counting the first letter as zero. var.substring(start,stop)
function DisplayFirstChar() {
MyText = prompt("Type some text", "")
alert(MyText.substring(0, 1))
}
The opposite of Substring
is the indexOf
property. Instead of returning the text at a certain position, it returns the position of a certain piece of text. For example, if I set MyText
equal to "Tupperware"
then the property MyText. indexOf("r")
would return a value of 5. "r"
is the sixth letter in, but again, JavaScript begins counting with zero.
function Display_r_position() {
MyText = prompt("Type some text containing an 'r'", "")
alert(MyText.indexOf("r"))
}
The +=
operator allows me to add text to the end of an existing variable. For example, if the variable MyText="cat"
then the command MyText+="erpillar"
would result in MyText
equalling "caterpillar"
This example will tack anything you type onto the word "cat"
function AddToCat() {
MyText = "cat"
AddOn = prompt("Type something to go after cat", "")
MyText += AddOn
alert(MyText)
}