The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string and the lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.
Both methods accept a second parameter as the starting position for the search:
The search() method searches a string for a specified value and returns the position of the match:
indexOf() and search() are quite equal. These are the differences between indexOf() and search():
- The search() method cannot take a second start position argument.
- The search() method can take much more powerful search values (regular expressions).
There are 3 methods for extracting a part of a string:
- slice(start, end)
- substring(start, end)
- substring() is similar to slice().
- The difference is that substring() cannot accept negative indexes.
- substr(start, length)
- substr() is similar to slice().
- The difference is that the second parameter specifies the length of the extracted part.
- If you omit the second parameter, substr() will slice out the rest of the string.
If you omit the second parameter, the method will slice out the rest of the string:
Negative positions do not work in Internet Explorer 8 and earlier.
The replace() method replaces a specified value with another value in a string. By default, the replace() function replaces only the first match:
To replace all matches, use a regular expression with a /g flag (global match):
By default, the replace() function is case sensitive. Writing MICROSOFT (with upper-case) will not work. To replace case insensitive, use a regular expression with an /i flag (insensitive):
The replace() method does not change the string it is called on. It returns a new string.
A string is converted to upper case with toUpperCase().
A string is converted to lower case with toLowerCase().
There are 2 safe methods for extracting string characters:
- charAt(position)
- charCodeAt(position)
unsafe method:
This is unsafe and unpredictable:
- It does not work in all browsers (not in IE5, IE6, IE7)
- It makes strings look like arrays (but they are not)
- str[0] = “H” does not give an error (but does not work)
If you want to read a string as an array, convert it to an array first.
A string can be converted to an array with the split() method: