Javascript string methods Summary.
**Note that these methods do not modify the string object itself, so the resulting string must be reassigned for the operation to be meaningful. In Javscript strings are immutable.
Length:
Although string length is not a method, it's a property - this is one of the most commonly used functionalities for a string.
str.length will return the length of the string, no brackets since this is a property
Template Literals (ES6):
Similar to C#, in JS it's possible to use back tics and dollar sign followed by curly brackets surrounding the variable name as place holders to format strings. This process is called "string interpolation".
E.g.
const myPet = 'dog';
console.log(`I own a ${myPet}`); //will output "I own a dog"
Get/From character:
In general use charAt() and charCodeAt(). To treat strings as arrays convert them first using var str_as_array = str.split("");
- charAt([index]) returns the character at the index
- charCodeAt([index]) returns the Unicode representation (integer 0 - 65535)
- str[index] returns the character at the index
- fromCharCode([unicode1], [unicode2], [unicode2] ... ) the reverse function of charCodeAt(), returns the character(s) from the unicode number(s)
Queries:
These methods are available IE11 or later. They can be replaced with indexOf() and seeing if the returned index is -1 if using IE10 or earlier
- startsWith([str]) returns true if a string starts with str
- endsWith([str]) returns true if a string ends with str
- includes([str]) returns true if str is a substring
Search for substring:
These methods will return -1 if the substring is not found. In general, use indexOf to search for first occurence of and lastIndexOf to search from end of the string. The search method is for more complex regular expressions. An additional optimization can be made to search from a starting index if the substring must be before/after a certain index. This only applies to indexOf and lastIndexOf methods, search() doesn't have this optional parameter.
- indexOf(substring, [startingSearchIndex])
- lastIndexOf(substring, [startingSearchIndex])
- search(substringOrRegex)
Splitting strings:
In general slice() will be sufficient for all variations of splitting strings in different places and also accepts negative indices to start counting from the end of the string. The end index is optional for these methods as it will assume the end of the string if end index is not given.
- slice([startInd], [endInd]) the end index is not included in the resulting string, use negative indices to count from end of string (IE9 and later). If the endInd is not given, the function assumes end of the string.
- substring([startInd], [endInd]) doesn't accept negative indices. The endInd is also optional similar to slice()
- substr([startInd], [length]), accepts negative indices like slice(), user-friendly option to provide length as second parameter
Edit strings:
- replace([existing], [new]) accepts regular expressions E.g. /existing/i for case-insenstive, /existing/g for global (replace all occurences)
- toUpperCase(), toLowerCase() to convert entire string to a certain case
- trim() removes whitespace (IE9 or later)
Convert to array:
Use split([delimiter]) to split a string into array
Examples:
- str.split(" ") to split sentences to array of words
- str.split('"") to convert string to array of characters (delimiter is empty string )
- str.split(",") to split comma-separated values into array of values
Special case str.split() will return an array with the entire string in first element of array or array[0]
Advanced:
If using IE8 or earlier, and trim or other functionalities do not exist, we can do the following to ensure that trim works by using replace with regex.
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
var str = " Hello World! ";
var trimmed = str.trim();