JavaScript · JS Tutorial · Lesson 15
JS String Methods
slice, replace, toUpperCase, trim, split and more.
String methods help you work with strings. Strings are immutable: methods return a new string.
Example
<p id="demo"></p>
<script>
let text = " Apple, Banana, Kiwi ";
let t = text.trim();
let out = "";
out += t.slice(7, 13) + "<br>";
out += t.toUpperCase() + "<br>";
out += t.replace("Kiwi", "Mango") + "<br>";
out += t.includes("Banana") + "<br>";
out += t.split(", ").length + " fruits<br>";
out += t.indexOf("Kiwi") + "<br>";
out += "5".padStart(3, "0");
document.getElementById("demo").innerHTML = out;
</script>
| Method | Does |
|---|---|
| slice(start, end) | Extracts part of a string |
| toUpperCase() / toLowerCase() | Changes case |
| trim() | Removes whitespace at both ends |
| replace() / replaceAll() | Replaces text |
| split(separator) | Converts a string to an array |
| includes() / startsWith() / indexOf() | Searches a string |
Keep reading “JS String Methods”
Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.