Most of the information that we key in today is either button clicks of various types or keying in of text. Take a simple example of login screens. In those screens, we enter the user name or the login name and then the password. Both are text that is combination of alphabets, numbers and symbols. One who runs the website should be able to process the text and validate that they are indeed correct and match against the records.
Text in computer terminology is usually called string. The string is a sequence of characters enclosed within single quotes or double quotes. The characters can be alphabets or numbers or even symbols. There are several predefined functions that have been written to work on and manipulate strings in Javascript.
Strings as character arrays
Now, an array is a set of elements that can be accessed with respect to their index. Similarly, one can treat a string as an array of characters and access them by using their index position. Here are some examples of how strings can be defined. Here too, array indices begin from zero. For the string “hello”, the indices count from 0 to 4 but the length of the string is 5. The quotes that begin and end should be of the same type.
var stringWithSingleQuotes = 'Hello World!'; var stringWithDoubleQuotes = "Hello World!"; var characterAtSecondPosition = stringWithSingleQuotes[1]; var characterAtZerothPosition = stringWithDoubleQuotes[0];
Quotes in a string
We saw that a string is supposed to be enclosed within either single quotes or double quotes. What if the string in itself contains these symbols? Then which quote is taken as the end? The solution to this problem is available in two forms.
The first is that, the string can contain quote that is NOT the same type as the enclosing quote. For example, if the string is contained within double quotes, then it can contain single quotes. If the string is contained within single quotes then it can contain double quotes.
The second solution is that one can use the escape character ‘\’. We’ll take the opportunity here to learn what an escape character is. The escape character combines with one or more characters to form an escape sequence. Each sequence behaves differently than when used without the escape character. Here are some commonly used predefined escape sequences.
Escape Sequence | Function performed |
\’ | Print the single quote |
\” | Print the double quote |
\\ | Print the backslash |
\n | Introduce a newline |
\r | Makes the carriage return to the beginning of the same line. |
\t | Introduce a tab space |
\b | Introduce a backspace |
\f | Introduce a form feed |
Now is it easy to see how you can include quotes within a string? Yes. These escape sequences can be a fool proof way to include quotes within a string.
var stringEnclosedInSingleQuotes = 'He said, "Come Here"'; var stringEnclosedInDoubleQuotes = "This is Ron's pen."; var doubleQuoteWithEscapeSequence = "He said, \"Come Here\""; var singleQuoteWithEscapeSequence = "This is Ron\'s pen.";
The length of the string
The length of a string is the number of characters that make up the string. Like said before, the maximum index in a string is one short of the length of the string since indices start numbering from zero.
var myString = "Hello"; document.write("The length of the string is" + myString.length);
Converting to a string
Var c = 124; Var d = c.toString();
Different data would be available. Sometimes a number would need to be stored as a string. In such cases one can use the toString function to convert to a string. Not much concern arises when converting to a string as any alphabet, number or symbol is simply stored as it is as a string.
Converting from a string
Converting a string to another type is very common in websites. Usually when a user enters information in user controls like text boxes it is treated as a string. The string is then converted to the desired type. During conversion to a number if the string contains characters that cannot be converted to a number, then Javascript simply returns NaN.
<!DOCTYPE html> <html> <head> <script type="text/javascript"> </script> </head> <body> Javascript converts the number to string when possible and returns a NaN when it cannot. <hr> <script type = "text/javascript"> var positiveSample = "5412"; var negativeSample = "4,34"; var number = positiveSample * 10; var notNumber = negativeSample * 10; document.write("Using number from string for multiplication " + number + ".<br/>"); document.write("Using a non number from string for multiplication yields " + notNumber + ".<br/>"); </script> </body> </html>
String Concatenation
Concatenation is the term given to join two or more strings. The ‘+’ symbol is used to join two strings and make them one. The string that appears on the left of the + comes first followed by the string that comes after the +. We have done this operation several times in the document.write function where we attach values from variables to strings. It is not necessary to join only two strings. One thing that should be noted is that when a number is added to a string then it is taken as concatenation and not addition.
<!DOCTYPE html> <html> <head> <script type="text/javascript"> </script> </head> <body> Javascript uses + to concatenate two strings. If a string is used with a number the + is taken as concatenation. <hr> <script type = "text/javascript"> var aNumber = "12"; var whatAppears = 12 + aNumber; document.write("The string that we get is " + whatAppears + ".<br/>"); </script> </body> </html>
The indexOf and lastIndexOf function
As mentioned earlier the string is a collection of characters. One can treat it as an array of characters with each character having an index position. The count starts from zero and ends at one minus the length of the string.
The indexOf function would return the index of a character or the starting index of the substring (part of the string).
The lastIndexOf function would return the index of a character or the starting index of the substring. Javascript would begin the search from right to left instead of the conventional left to right.
In case the character or the substring is not found then Javascript returns -1 as the result.
<!DOCTYPE html> <html> <head> <script type="text/javascript"> </script> </head> <body> A Demonstration of the indexOf and lastIndexOf function in Javascript. <hr> <script type = "text/javascript"> var sample = "String Sample"; document.write("The first occurence of S in sample is " + sample.indexOf("S") + ".<br/>"); document.write("The last occurence of S in sample is " + sample.lastIndexOf("S") + ".<br/>"); document.write("The occurence of Sam in sample is " + sample.indexOf("Sam") + ".<br/>"); document.write("The occurence of Sum in sample is " + sample.indexOf("Sim") + ".<br/>"); </script> </body> </html>
charAt function
This function can return the character at a particular index from a string. Valid results will be returned from zero to one minus the length of the string. If the index falls out of the range then no character is returned.
<!DOCTYPE html> <html> <head> <script type="text/javascript"> </script> </head> <body> A Demonstration of the charAt function. <hr> <script type = "text/javascript"> var sample = "String Sample"; document.write("The character at the first position is \"" + sample.charAt(0) + "\".<br/>"); document.write("The character at the seventh position is \"" + sample.charAt(6) + "\".<br/>"); document.write("The character at the fifteenth position is \"" + sample.charAt(15) + "\".<br/>"); </script> </body> </html>
Splitting a string
One can split strings in Javascript using the split function. Here one would be required to specify the delimiter based on which the string will be split.
<!DOCTYPE html> <html> <head> <script type="text/javascript"> </script> </head> <body> A Demonstration of the split function. <hr> <script type = "text/javascript"> var sample = "String Sample"; document.write("Splitting the string based on space " + sample.split(" ") + "<br/>"); document.write("Splitting the string based on S " + sample.split("S") + "<br/>"); </script> </body> </html>
Changing the case of string
There may arise occasions when one would need to change a string to uppercase totally or to lower case totally. There are functions for this specific purpose toUpperCase() and toLowerCase().
<!DOCTYPE html> <html> <head> <script type="text/javascript"> </script> </head> <body> A Demonstration of the case change functions. <hr> <script type = "text/javascript"> var sample = "String Sample"; document.write("The string " + sample + ", when converted to lower case, becomes " + sample.toLowerCase() + ".<br/>"); document.write("The string " + sample + ", when converted to upper case, becomes " + sample.toUpperCase() + ".<br/>"); </script> </body> </html>
Retrieving substrings from string
A substring is a part of a string. The substring(first_index, last_index) will retrieve a substring that begins at the first_index and ends at the last_index. The substr(first_index,number_of_characters) will retrieve the substring that begins at the first_index and ends after retrieving the specified number of characters.
<!DOCTYPE html> <html> <head> <script type="text/javascript"> </script> </head> <body> A Demonstration of the substring functions. <hr> <script type = "text/javascript"> var sample = "String Sample"; document.write("Retrieving the substring with indices is \"" + sample.substring(3,9) + "\" .<br/>"); document.write("Retrieving the substring with index and number of characters is \"" + sample.substr(6,5) + "\" .<br/>"); </script> </body> </html>