Strings in JavaScript
By: aathishankaran in JavaScript Tutorials on 2007-03-29
Strings are a fundamental part of any programming language. Strings, which are a set of alpha-numeric characters, can be either a literal string, such as "Push the envelope" or a variable representing a string, such as the Phrase. A string can also be treated as an object, complete with its own suite of methods and properties.
Creating a String Object
Use the following procedure to create a string object.
var str_obj =new String([message])
Example:
<SCRIPT>
var str = new String("My name is Richard" )
alert (str. length)
</SCRIPT>
Working with Strings
Because strings are one of the primary types of data you have to work with, it is critical to have some way of extracting data from strings and obtaining information about strings. JavaScript has the properties and methods
Method/Property |
Description |
length |
Returns an integer representing the value of size of the string. |
charAt (pos) |
Returns the character at the specified index. |
indexOf (searchText [,startPos]) |
Returns the index of the first occurrence of SearchText. |
lastIndexOf(searchText [,endPos]) |
Returns the index of last occurrence of searchText |
substring (startPos, endPos) |
Returns the substring of the string starting at startpos and ending at endPos |
Determining String Lengths
You can use the String object's length property to determine the size of a string.
For example, the following code returns 17:
"Crazy Legs Nelson".length
The following code returns 16:
var str = "This is the day."
len = str.length
Searching Within Strings
You can search for text within strings by using indexOf() and lastIndexOf(). Use these methods when you want to search for a particular character or substring within a string and return the position (or index) of the occurrence within the string. Whereas indexOf() starts at the left of the string and moves right, lastIndexOfO does the same operation but starts at the left. Both indexOf() and lastIndexOfO start at the 0 position for the first character encountered, and both return a value of -1 if the search text is not found. For example, the following code re-turns a value of 3:
"Time and time again".indexOf("e")
On the other hand, the following code returns a value of 12:
"Time and time again".lastIndexOf("e")
Both methods have an optional second parameter that enables you to specify here in the string you want to start the search. For example, the script shown n Listing 14.1 searches through the variable graf and counts the number of occurrences of the letter 'e'.
<SCRIPT> pos = 0 num = -1 i = -1 var graf = "While nearly everyone agrees on the principle of reuse, the priority we give it varies wildly." while (pos != -1) { pos = graf.indexOf("e",i+1) num += 1 i = pos } document.write(graf) document.write("<p><p>") document.write("There were" + num + " e' s in that paragraph.") </SCRIPT>
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
Comments