JavaScript String Methods
JavaScript strings come with many built-in methods for searching, extracting, and transforming text.
Working with String Methods
A string method is a built-in function attached to every string value. You call it with dot notation after the string. Because strings are immutable, these methods never modify the original text — they return a new value that you can store in a variable or use directly.
- Changing case: toUpperCase() and toLowerCase()
- Trimming whitespace: trim(), trimStart(), trimEnd()
- Searching: indexOf(), includes(), startsWith(), endsWith()
- Extracting: slice(), substring(), charAt()
- Replacing and splitting: replace(), replaceAll(), split()
Case and whitespace
<!DOCTYPE html>
<html>
<body>
<h2>Case and whitespace</h2>
<script>
let raw = " Hello World ";
console.log(raw.trim()); // "Hello World"
console.log(raw.trim().toUpperCase()); // "HELLO WORLD"
console.log("HELLO".toLowerCase()); // "hello"
// The original is unchanged
console.log(raw); // " Hello World "
</script>
</body>
</html>To find text inside a string, indexOf() returns the position of the first match, or -1 when nothing is found. When you only care whether the text exists, includes() returns a simple true or false, which reads more clearly in conditions.
Searching within a string
<!DOCTYPE html>
<html>
<body>
<h2>Searching within a string</h2>
<script>
let sentence = "The quick brown fox";
console.log(sentence.indexOf("quick")); // 4
console.log(sentence.indexOf("cat")); // -1
console.log(sentence.includes("fox")); // true
console.log(sentence.startsWith("The")); // true
console.log(sentence.endsWith("dog")); // false
</script>
</body>
</html>Extracting and replacing
<!DOCTYPE html>
<html>
<body>
<h2>Extracting and replacing</h2>
<script>
let text = "JavaScript";
console.log(text.slice(0, 4)); // "Java"
console.log(text.slice(-6)); // "Script"
let msg = "I like cats, cats are great";
console.log(msg.replace("cats", "dogs")); // replaces first only
console.log(msg.replaceAll("cats", "dogs")); // replaces every match
console.log("a,b,c".split(",")); // ["a", "b", "c"]
</script>
</body>
</html>Because each method returns a string, you can chain several calls together. Each step operates on the result of the previous one, which lets you clean and reshape text in a single expression.