General method of using String Object is to declare a variable and assign a string, in other words a text to the variable.
assigns the text Welcome to the variable exf defined.
We have seen in earlier section that some of the methods used in String Objects are:
indexOf method of String Object:
If a programmer wants to know the position of a characters or group of characters in a String Object it can be obtained by applying the indexOf method to the String. In other words indexOf method of the String Object returns the position of the first occurrence of a specified string value in a string.
Here the substr given in argument is searched in the string and if it found the index number of the searched character is or substring within the string is returned. If it is not found then -1 is returned. The default returned value is 0. The start is an optional argument specifying the position within string to begin the search.
Output of the above program is:
This is because the first write statement has Welcome given as substring in the indexOf method and since it occurs in the starting of the String Object the value 0 is printed. The second write statement has Members given as substring in the indexOf method and since it does not occur in the string the value -1 is printed. Only members is present in the String Object and not Members so -1 is printed.
lastIndexOf method of String Object:
General syntax of lastIndexOf method of String Object is as follows:
In this the substring given in parameters is searched for in the String and if it is found the index number of the searched character or substring within the string is returned. Here the order of search is from end to beginning of the String. If it is not found the value returned is -1. Start is an optional argument specifying the position within string to begin the search. Default is string.length-1.
will give a value of 3. This is because the position of text o appearing in the string is counted from the end of string and the end of string is equal to stringlenth -1 which is equal to 4 and so position of o appearing in the string is 3.
substring method of String Object:
In this method characters in the string between from and to indexes is returned "to" is optional, and if omitted, characters up to the end of the string is returned.
Output of the above program is
This is because the first substring extracts text starting from the first till the second character which gives Wel as output and the second substring extracts text starting from the fourth till the end of string as the optional to is not specified.
We have seen only some of the methods of the String Object above. Apart from these, there are many other methods available for String Object like split, slice, charAt, concat, replace.