String Things

Characters in a string are indexed from left to right with the first character being 0, Javascript counts from zero. The number of the last character would be string length-1
If the number you supply is out of range, JavaScript returns an empty string.

charAt

Returns the specified character from a string.

charAt(number)

number = Between 0 and 1 less than the length of the string.

Example

<script type="text/javascript">
<!--
var my_string = "JavaScript"
alert(my_string.charAt(0)) // = J
alert(my_string.charAt(1)) // = a
alert(my_string.charAt(2)) // = v
alert(my_string.charAt(3)) // = a
alert(my_string.length) // = 10 (ten letters in the word Javascript)
//-->
</script>

Alertbox Example


charCodeAt

Returns a number indicating the ISO-Latin-1 codeset value of a character at the given index.

charCodeAt(index)

index = An integer between 0 and 1 less than the length of the string. The default value is 0.

The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct match of the ASCII character set.

Example

var my_string = "JavaScript"
my_string.charCodeAt(0) = 74
my_string.charCodeAt(1) = 97
my_string.charCodeAt(2) = 118
my_string.charCodeAt(3) = 97

Alertbox Example


fromCharCode

Returns a string created by using the specified sequence ISO-Latin-1 codeset values.

fromCharCode(num1, ..., numN)

num1, ..., numN = A sequence of numbers that are ISO-Latin-1 codeset values.

This method returns a string and not a String object.

Because fromCharCode is a static method of String, you always use it as String.fromCharCode(), rather than as a method of a String object you created.

The following example returns the string "Javascript".

String.fromCharCode(74,97,118,97,115,99,114,105,112,116)

Alertbox Example

The which property of the KeyDown, KeyPress, and KeyUp events contains the ASCII value of the key pressed at the time the event occurred. If you want to get the actual letter, number, or symbol of the key, you can use fromCharCode.

The following example returns the letter, number, or symbol of the KeyPress event's which property.

String.fromCharCode(KeyPress.which)


indexOf

Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, or -1 if the value is not found.

indexOf(searchValue, fromIndex)

searchValue = A string representing the value to search for.

fromIndex (Optional) = The location within the calling string to start the search from. It can be any integer between 0 and 1 less than the length of the string. The default value is 0.

The indexOf method is case sensitive. For example, the following expression returns -1:

"Blue Whale".indexOf("blue")

Example

The following example uses indexOf and lastIndexOf to locate values in the string

"Mary had a little lamb its fleece was white as snow"

var my_string="Mary had a little lamb its fleece was white as snow"
document.write('<P>The index of the first letter "a" from the beginning is ' +my_string.indexOf('a')) // Displays 1
document.write('<P>The index of the first letter "a" from the end is ' +my_string.lastIndexOf('a')) // Displays 44
document.write('<P>The index of the word "lamb" from the beginning is '+my_string.indexOf('lamb')) // Displays 18
document.write('<P>The index of the word "white" from the end is '+my_string.lastIndexOf('white')) // Displays 38
document.write('<P>The index of the word "is" in the string is ' +my_string.indexOf('is')) // Displays -1 because the string does not contain the word "is".


Character Count

The following script shows how you can used the indexOf() method to search through selected text for the number of times a particular letter in used.
Enter Some Text

. . . . . . . . . . . . . . . . . . . .

Character to count

<script type="text/javascript">
<!--
function charCount(){
searchString=myForm.Text.value // text to search
charPos = searchString.indexOf(myForm.letter.value) // position of char to count
searchChar=myForm.letter.value // character to search for
charPos = searchString.indexOf(searchChar) // position of char

count = 0

while(charPos != -1){
count++
charPos = searchString.indexOf(myForm.letter.value,charPos+1) // number of occurances
}

// for no occurances
if(count==0){
document.getElementById("show").innerHTML=("There is no \" <font color=red><b> " 
+myForm.letter.value+"</b></font> \" in the text above")
}

// for one occurance
if(count==1){
document.getElementById("show").innerHTML=("There is only <b>" +count+ "<font color=red> " 
+myForm.letter.value+"</b></font> in the text above")
}

// for spaces
if(myForm.letter.value==" "){
document.getElementById("show").innerHTML=("There are " +count+ " spaces  's in the text above")
}
else{
// for more than one occurance
if(count>1){
document.getElementById("show").innerHTML=("There are <b>" +count+ "<font color=red> " 
+myForm.letter.value+"</b></font> 's in the text above")
}

}

}
//-->
</script>

<form name="charactercount">
Enter Some Text <input type=text name=Text size=50>
<P>Enter letter to count <input type=text name=letter size=2 onKeyup=charCount() onKeydown=select()>
</form>


The following example iterates through an array and counts the number of specified characters within the string

string[0] = "This test counts how many times each vowel has been used in these strings"
string[1] = "Any number of indexes can be used"
string[2] = "With any number of vowels"
string[3] = "The script can give the total for each index or the collective total"

<script type="text/javascript">
<!--
var string = new Array()
string[0] = "This test counts how many times each vowel has been used in these strings"
string[1] = "Any number of indexes can be used"
string[2] = "With any number of vowels"
string[3] = "The script can give the total for each index or the collective total"

collectiveCount=0 // 0 = results for each index, 1 = total results for all indexes

vowel=new Array("a","e","i","o","u")

characterCount=new Array()

function initCount(){

for(var i=0;i<string.length;i++){
checkString=string[i].toLowerCase()

for(var j=0;j<vowel.length;j++){

if(collectiveCount==1){
if(i==0){characterCount[j]=0}
}
else{
characterCount[j]=0
}

nextCharacter=checkString.indexOf(vowel[j])

while(nextCharacter!=-1){
characterCount[j]++
nextCharacter=checkString.indexOf(vowel[j],nextCharacter+1)
}

}

if(collectiveCount==0){
document.getElementById("display").innerHTML+="The number of vowels in the string at index "+i+" are:<br>"

for(k=0;k<characterCount.length;k++){
document.getElementById("display").innerHTML+=vowel[k].toUpperCase()+" = "+characterCount[k]+"    "
}
document.getElementById("display").innerHTML+="<br><br>"
}

}

if(collectiveCount==1){
for(k=0;k<characterCount.length;k++){
document.getElementById("display").innerHTML+="Number of character "+vowel[k].toUpperCase()+" = "+characterCount[k]+" <br>"
}
}

}

// add onload="initCount()" to the opening BODY tag

//-->
</script>

<div id="display"></div>


substring

Returns a subset of a String object.

substring(indexA, indexB)

indexA = An integer between 0 and 1 less than the length of the string.

indexB = An integer between 0 and 1 less than the length of the string.

substring extracts characters from indexA up to but not including indexB.
In particular:

If indexA is less than 0, indexA is treated as if it were 0.
If indexB is greater than my_string.length, indexB is treated as if it were my_string.length.
If indexA equals indexB, substring returns an empty string.
If indexB is omitted, indexA extracts characters to the end of the string.

Using LANGUAGE="JavaScript1.2" in the SCRIPT tag,
If indexA is greater than indexB, JavaScript produces a runtime error (out of memory).

Without LANGUAGE="JavaScript1.2",
If indexA is greater than indexB, JavaScript returns a substring beginning with indexB and ending with indexA - 1.

Example 1.
The following example uses substring to display characters from the string "Mary had a little lamb its fleece was white as snow":

var my_string="Mary had a little lamb its fleece was white as snow"
document.write(my_string.substring(0,4)) // Displays "Mary"
document.write(my_string.substring(5,8)) // Displays "had"
document.write(my_string.substring(9,10)) // Displays "a"
document.write(my_string.substring(11,17)) // Displays "little"
document.write(my_string.substring(18,22)) // Displays "lamb"

Example 2.
The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string "Mary had a little lamb" into "Mary had a little cat".

function replaceString(oldS,newS,fullS) { // Replaces oldS with newS in the string fullS
for (var i=0; i<fullS.length; i++) {
if (fullS.substring(i,i+oldS.length) == oldS) {
fullS =fullS.substring(0,i)+newS+fullS.substring(i+oldS.length,fullS.length)
}
}
return fullS
}

replaceString("lamb","cat","Mary had a little lamb")

See Example 2

Palindrome

Enter a string:
Reversed string: