Javascript strings are sequences of characters; they can be alphanumeric, ideographic, or in a variety of encodings. These strings always count from 0 as their first character. The Javascript standard provides more than a dozen methods to execute complex manipulations of strings.

Javascript string methods provide complex operations in the same way as Javascript array methods handle arrays. Some Javascript string methods are similarly named to Javascript array methods and provide similar functionality.

Javascript operators, although they can act on strings, are not Javascript string methods. The length property of a string is also not considered a method.

This article describes the many complex operations available through Javascript string methods.

Javascript String Methods that Return Locations

Some Javascript string methods return the location of specific string parts. These methods come in two variants: those that return the string index where something is found and those that return the character found at a certain location.

IndexOf() and LastIndexOf()

The indexOf() method returns the position within a string where the first occurrence of a specified substring can be found. The lastIndexOf() method does the same thing, finding the last occurrence of a specified substring rather than the first. Both methods return -1 if the substring cannot be found.

let example1a = "abcdabc";
let example1b = example1a.indexOf("abc");      // 0
let example1c = example1a.lastIndexOf("abc");  // 4

Both of these methods also take a second parameter that identifies where the string search should start. The indexOf() method traverses the string from the beginning, while the lastIndexOf() method traverses the string from the end.

let example1a = "abcdabc";
let example1d = example1a.indexOf("abc", 3);      // 4
let example1e = example1a.lastIndexOf("abc", 3);  // 0

Search()

The search() method returns the position within a string where the first occurrence of a specified substring can be found, similar to the indexOf() method. The search() method can find regular expression matches.

let example1a = "abcdabc";
let example1f = example1a.search("a..d");  // 0

CharAt() and CharCodeAt()

The charAt() method returns the character at a specific position in a string, while the charCodeAt() method returns the UTF-16 character code corresponding to the character at a specific string position. The UTF-16 character code is always between 0 and 65535.

let example2a = "Hi there!";
let example2b = example2a.charAt(0);      // H
let example2c = example2a.charCodeAt(0);  // 72

Javascript String Methods that Create Substrings

Three Javascript string methods exist to return substrings from inside string queries. Each of them works in a slightly different way, depending on how you want to create the substring.

Slice()

The slice() method extracts part of a given string and returns that substring.

It requires one parameter: the start position of the substring. The substring includes the start position and the rest of the string after it. Alternatively, the slice() method can take a second parameter specifying where the substring should stop. The substring does not include the specified stop index.

Either parameter to the slice() method can be positive or negative. Positive parameters count forward from the first character in the string, while negative parameters count backward from the last character in the string.

let example3a = "abcdefghijklmnopqrstuvwxyz";
let example3b = example3a.slice(5);       // "fghijklmnopqrstuvwxyz"
let example3c = example3a.slice(-10);     // "qrstuvwxyz"
let example3d = example3a.slice(5, 8);    // "fgh"
let example3e = example3a.slice(-10, -6); // "qrst"

Substring()

The substring() method works identically to the slice() method except that it cannot take negative string indexes as parameters (all “distances” are measured from the front of the string).

let example3a = "abcdefghijklmnopqrstuvwxyz";
let example3f = example3a.substring(5);     // "fghijklmnopqrstuvwxyz"
let example3g = example3a.substring(5, 8);  // "fgh"

Substr()

The substr() method works identically to the slice() method except that its second parameter specifies the substring length, rather than the stop index position.

let example3a = "abcdefghijklmnopqrstuvwxyz";
let example3h = example3a.substr(5);      // "fghijklmnopqrstuvwxyz"
let example3i = example3a.substr(-10);    // "qrstuvwxyz"
let example3j = example3a.slice(5, 8);    // "fghijklm"
let example3k = example3a.slice(-10, -6); // "opqrst"

Javascript String Methods that Change Strings

Javascript strings are immutable; that is, they cannot be changed once they have been created. Javascript string methods that “change” strings actually return new strings, but they give the appearance of changing strings directly thanks to their names being action words.

Replace()

The replace() method finds a substring and replaces it with another. The replacement is case sensitive. In this example, the first call to replace() would not be successful, but the second call would.

let example4a = "Please visit the UDY blog!";
let example4b = example4a.replace("UdY", "Udacity");
let example4c = example4a.replace("UDY", "Udacity");

ToUpperCase() and ToLowerCase()

The toUpperCase() and toLowerCase() methods convert a string into uppercase and lowercase, respectively.

let example5a = "Udacity";
let example5b = example5a.toUpperCase();  // "UDACITY"
let example5c = example5a.toLowerCase();  // "udacity"

Split()

The split() method converts a string into an array. If you do not pass a delimiter string to this method, it will return an array that contains the entire string in the first array index. An empty string delimiter causes this method to return an array of single characters.

let example5a = "Udacity";
let example5e = example5a.split();    // ["Udacity"]
let example5f = example5a.split("");  // ["U","d","a","c","i","t","y"]
let example5g = example5a.split("a"); // ["Ud","city"]

Trim()

The trim() method removes leading and trailing whitespace from a string.

let example6a = "    Welcome to Udacity!   ";
let example6b = example6a.trim();  // "Welcome to Udacity!"

PadStart() and PadEnd()

The padStart() and padEnd() methods pad the beginning or end of a string, respectively, by adding a specified number of characters onto the string until the string reaches the desired length. The first parameter is the desired string length, and the second parameter is the padding character.

These methods are relatively new; they were added to the Javascript standard in 2017.

let example7a = "1";
let example7b = example7a.padStart(4,"a");  // "aaa4"
let example7c = example7a.padEnd(5, "b");   // "5bbbb"

Conclusion

There are many Javascript string methods that have similar functions, but they all have distinct purposes. The padStart() and padEnd() methods are the most recent additions to the string method lexicon.

These methods provide information about strings and can create new strings, making string processing in Javascript fast and easy. Always remember to pick the right string method at the right time to maximize speed and efficiency.

Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript string methods and other programming concepts.

Start Learning

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni