Strings are one of the most common JavaScript data types. They represent text and come with many built-in methods.

Check string length

const text = "Hello";
console.log(text.length); // 5

Convert to upper/lower case

const text = "Hello World";
console.log(text.toUpperCase()); // "HELLO WORLD"
console.log(text.toLowerCase()); // "hello world"

Extract part of a string

Common methods include:

  • slice
  • substring
  • substr (legacy, generally avoid in new code)
const text = "JavaScript";
console.log(text.slice(0, 4)); // "Java"
console.log(text.substring(4, 10)); // "Script"

Search inside a string

const text = "I love JavaScript";
console.log(text.includes("Java")); // true
console.log(text.indexOf("Java")); // 7
console.log(text.startsWith("I")); // true
console.log(text.endsWith("Script")); // true

Replace content

const text = "Hello Tom";
console.log(text.replace("Tom", "Alice")); // "Hello Alice"

Remove spaces

const text = " hello world ";
console.log(text.trim()); // "hello world"
console.log(text.trimStart()); // "hello world "
console.log(text.trimEnd()); // " hello world"

Split strings

const sentence = "I love JavaScript and Node.js";
const words = sentence.split(" ");
console.log(words);
// ["I", "love", "JavaScript", "and", "Node.js"]

Repeat strings

"ha".repeat(3); // "hahaha"

Template literals

Template literals make string interpolation and multi-line strings easier.

const name = "Tom";
console.log(`Hello, ${name}`);

Summary

The most common string operations in daily development are:

  • length checking
  • case conversion
  • slicing
  • searching
  • replacing
  • trimming
  • splitting

If you are comfortable with these, you can handle most text manipulation tasks in JavaScript.