All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
- length
find a string in a string:
- indexOf(str, start(optional))
- lastIndexOf(str, start(optional))
- search(str/regex)
extracting string parts
- slice (start, end(optional, end not included)) -> returns the sliced string, (takes negative index, Negative positions do not work in Internet Explorer 8 and earlier.
)
- substring (start, end (optional)) -> similar to slice but can't accept negative indexes
- substr (start, length(optional)) -> takes negative parameter for the start
replace a string content
- replace(toBeReplaced, new str) -> only replace the first match, and the updated string is returned, the string it called on is not changed
- can use regex to replace insensitive and global matches
- .toUpperCase()
- .toLowerCase()
- the original string is not changed
var text3 = text1.concat(" ",text2,"check","another one"); -> join two or more strings
String.trim() -> removes white spaces on both sides of the string
You can also use the replace solution above to add a trim function to the JavaScript String.prototype:
Extracting String Characters
- charAt(position)
- charCodeAt(position)
- Property access [ ] //not recommend
Converting a String to an Array
txt.split("char")
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is "", the returned array will be an array of single characters: