String Methods

Built-in methods to transform and inspect strings.

Syntaxstr.toUpperCase() str.trim() str.replace(a, b)

Strings come with many built-in methods. A few essentials:

  • toUpperCase() / toLowerCase() — change case.
  • trim() — remove whitespace from both ends.
  • replace() — swap text.
  • repeat() — repeat a string.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Normalise a user's email input to lowercase before comparing it against stored credentials.
  • Trim whitespace from a form field value before validating its length.
  • Replace placeholder tokens in an email template with the user's actual name and order details.

More examples

Trim and lowercase an email

Chains trim() and toLowerCase() to normalise an email address from user input.

Example · js
const email = "  [email protected]  ";
const normalised = email.trim().toLowerCase();
console.log(normalised); // "[email protected]"

includes startsWith endsWith

Uses startsWith, includes, and endsWith to inspect parts of a URL string.

Example · js
const url = "https://api.example.com/users";
console.log(url.startsWith("https"));  // true
console.log(url.includes("/users"));   // true
console.log(url.endsWith(".json"));    // false

Replace placeholder tokens

Uses replace() to substitute placeholder tokens in an email template with real values.

Example · js
const tpl = "Hello {{name}}, your order {{id}} is ready.";
const msg = tpl.replace("{{name}}", "Alice").replace("{{id}}", "ORD-001");
console.log(msg);

Discussion

  • Be the first to comment on this lesson.
String Methods — JavaScript | SoundsCode