Previous
Getting Information 
Next
Finished 
ABC of JavaScript : An Interactive JavaScript Tutorial
String Manipulation

String Manipulation

String Manipulation can be used to format and validate user entries in forms. But I have not yet taught you how to get values from forms. I will go into detail how to get values from form in the advanced section, but for our purposes let me show you how to do it.

var txt = document.frm.entry.value;

Assuming that there is a form element with the name entry. You can make it with this code.
<form name="frm">
<input type="text" name="entry" value="Life is wonderful. Without it we'd all be dead." size=50 />
</form>
This code will create a text box like this.


But make sure that the script code is executed after the HTML code is fully loaded. Otherwise an error will be displayed.

Now we have the contents of the entry field in the variable 'txt'. Now to manipulate it.

Let us convert it to upper case and to lower case.

alert("Original : "+txt+"\nLower Case : " +txt.toLowerCase()+"\nUpperCase : "+txt.toUpperCase())

Finding its length and a charecter at a specified location.

alert("Length : "+ txt.length +"\nFourth Character : "+ txt.charAt(3))

Notice that I gave 'txt.charAt(3)' when I wanted the fourth character. This is because the string's first element is 0 like the array.

Now to find all characters from the 3rd place to the 6th place

alert("Characters : "+txt.slice(2,5))

Search for a regular expression and replace it.

var txt = document.frm.entry.value
//Searching
var re = /life\s/gi;
if(txt.match(re)) {
alert(re+" Found.")
} else {
alert(re+" is not found")
}
//Replacing
var encrypted = txt.replace(/(.)(.)(.)(.)(.)(.)(.)/g,"$3$6$7$1$2$4$5")
var decrypted = encrypted.replace(/(.)(.)(.)(.)(.)(.)(.)/g,"$4$5$1$6$7$2$3")
alert("Binny's Cheap Encryption of '"+txt+"' is...\n"+encrypted+
"\nAnd it decryption is...\n"+decrypted)

Here, the replace function will search for the given regular expression and replace it with the string given as the second argument. You can also use this function to replace simple strings.


var txt = document.frm.entry.value
//Replacing
var replaced = txt.replace("Life","Earth")
alert("After replace : " + txt
+"\nAfter replace : " + replaced)

Split a string to create an array

var txt = document.frm.entry.value
var arr = txt.split(" "); //Create an array with all the words as elements
alert("The array is "+arr+"\nThe first word is "+arr[0])

There is a lot of other stuff you can do with strings - see the Javascript Reference for more details.

Previous
Getting Information 
Next
Finished 
blog comments powered by Disqus