← Back to JavaScript Course | Chapter 3: Strings, Arrays & Data | Lesson 2 of 6

JS String Methods

Think of a text editor's toolbar, buttons for uppercase, trimming extra spaces, finding and replacing words, each one does one specific, well-defined job to transform your text. JavaScript strings come with a whole toolbar of built-in methods just like that, letting you change case, cut out parts of a string, search for specific words, or split a sentence into individual pieces, all without writing that logic yourself. These methods are used constantly in real applications, from formatting a tutorial title on cookiescursor.com to validating a visitor's typed email address.
Syntax
javascript
string.length;
string.slice(start, end);
string.replace(old, new);
string.split(separator);
string.toUpperCase();

Changing Case

toUpperCase() converts every letter in a string to uppercase, and toLowerCase() converts every letter to lowercase, both returning a brand new string rather than changing the original.

Note: Converting both sides of a comparison to the same case, with toLowerCase(), is a common trick for case-insensitive matching.
Warning: Since strings are immutable, calling toUpperCase() without storing its result does nothing useful, you must capture the returned value.

Example: Changing Case

javascript
// Declare the constant `text`, set to "Hello World"
// Declare the constant `text`, set to "Hello World"
const text = "Hello World";
// Print `text.toUpperCase()` to the console
// Print `text.toUpperCase()` to the console
console.log(text.toUpperCase());
// Print `text.toLowerCase()` to the console
// Print `text.toLowerCase()` to the console
console.log(text.toLowerCase());

trim

trim() removes whitespace from the beginning and end of a string, which is especially useful for cleaning up user-typed input that might contain accidental leading or trailing spaces.

Note: Always trim user input from a form field before validating it, extra spaces are easy for a visitor to type without noticing.
Warning: trim() only removes whitespace from the edges of a string, spaces in the middle of the text are left untouched.

Example: trim

javascript
const input = "   hello   ";
console.log(`"${input.trim()}"`);

slice and substring

slice(start, end) and substring(start, end) both extract a portion of a string based on index positions, slice supports negative indexes counting from the end, while substring treats negative values as zero.

Note: For most cases, slice() is the more flexible and predictable choice, especially when working with positions relative to the end of a string.
Warning: Both methods extract up to, but not including, the end index, forgetting this off-by-one detail is a common source of bugs.

Example: slice and substring

javascript
// Declare the constant `text`, set to "JavaScript"
// Declare the constant `text`, set to "JavaScript"
const text = "JavaScript";
// Print `text.slice(0, 4)` to the console
// Print `text.slice(0, 4)` to the console
console.log(text.slice(0, 4));
// Print `text.slice(-6)` to the console
// Print `text.slice(-6)` to the console
console.log(text.slice(-6));
// Print `text.substring(0, 4)` to the console
// Print `text.substring(0, 4)` to the console
console.log(text.substring(0, 4));

replace and replaceAll

replace() swaps the first match of a specified text or pattern with new text, while replaceAll() swaps every matching occurrence throughout the entire string.

Note: If you only want to replace one specific occurrence deliberately, replace() is correct, otherwise reach for replaceAll() to be thorough.
Warning: Using replace() when you actually needed every occurrence changed is a common bug, since only the first match gets updated.

Example: replace and replaceAll

javascript
// Declare the constant `text`, set to "cat cat cat"
// Declare the constant `text`, set to "cat cat cat"
const text = "cat cat cat";
// Print `text.replace("cat", "dog")` to the console
// Print `text.replace("cat", "dog")` to the console
console.log(text.replace("cat", "dog"));
// Print `text.replaceAll("cat", "dog")` to the console
// Print `text.replaceAll("cat", "dog")` to the console
console.log(text.replaceAll("cat", "dog"));

split, includes, startsWith, and endsWith

split() breaks a string into an array of pieces based on a separator, while includes(), startsWith(), and endsWith() each check for the presence of specific text at any position, the start, or the end of a string.

Note: split() is especially handy for turning a comma-separated list, like tags or categories, into a usable array.
Warning: includes(), startsWith(), and endsWith() are all case sensitive by default, normalize casing first if that matters for your check.

Example: split, includes, startsWith, and endsWith

javascript
// Declare the constant `tags`, set to "html,css,js"
// Declare the constant `tags`, set to "html,css,js"
const tags = "html,css,js";
// Print `tags.split(",")` to the console
// Print `tags.split(",")` to the console
console.log(tags.split(","));
// Print `tags.includes("css")` to the console
// Print `tags.includes("css")` to the console
console.log(tags.includes("css"));
// Print `tags.startsWith("html")` to the console
// Print `tags.startsWith("html")` to the console
console.log(tags.startsWith("html"));
// Print `tags.endsWith("js")` to the console
// Print `tags.endsWith("js")` to the console
console.log(tags.endsWith("js"));
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting that string methods return a brand new string rather than modifying the original, strings in JavaScript are immutable.
  2. Confusing slice() and substring(), they behave similarly but handle negative indexes differently.
  3. Using replace() when you meant replaceAll(), replace() only changes the first matching occurrence by default.
Chapter Summary
  • toUpperCase, toLowerCase, and trim adjust a string's casing or remove surrounding whitespace.
  • slice, substring, split, and includes/startsWith/endsWith let you extract or search within a string.
  • replace and replaceAll swap out matched text, with replaceAll affecting every occurrence.
Browser Support

All core string methods, including replaceAll, are supported in every current browser version.

🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.