JavaScript's built-in string methods let you inspect, transform, search and extract text without writing loops from scratch. The shortest working set to know is: length, charAt(), slice(), substring(), toUpperCase(), toLowerCase(), trim(), split(), replace(), replaceAll(), includes(), startsWith(), endsWith(), indexOf(), padStart(), padEnd(), repeat(), concat() and match(). This guide walks through each one with a concrete example, then covers the mistakes that trip people up and how to fix them.
What You'll Need
- A modern browser (Chrome, Edge, Firefox or Safari) with the developer console open, or Node.js installed if you prefer the terminal.
- Basic familiarity with declaring variables and calling functions.
- No libraries or frameworks — every method below is part of the standard JavaScript language.
Step-by-Step
- Open a place to run code. In a browser, press F12 (or right-click the page and choose Inspect), then select the Console tab. In Node.js, run
nodein your terminal. Labels in the developer tools can differ slightly by browser and version, but the Console tab is always present. - Create a test string. Type
const s = " Hello, World! ";and press Enter. You will reusesfor the examples below. - Check the length. Run
s.length. It returns the number of UTF-16 code units, including the leading and trailing spaces. This is a property, not a function, so do not add parentheses. - Trim whitespace. Run
s.trim()to remove spaces from both ends. Uses.trimStart()ors.trimEnd()to remove only one side. None of these changes; they return a new string. - Change case. Run
s.toUpperCase()ands.toLowerCase(). Both return new strings and leave the original untouched. - Get a single character. Run
s.charAt(2)to get the character at index 2 (zero-based). For direct access you can also use bracket notation:s[2]. Out-of-range indexes return an empty string withcharAt()andundefinedwith brackets. - Extract part of a string. Run
s.slice(2, 7)to take characters from index 2 up to but not including index 7. Negative indexes count from the end:s.slice(-3)gives the last three characters.substring(start, end)works similarly but swaps arguments if start is greater than end and treats negative values as zero. - Search inside a string. Run
s.includes("World")for a true/false check,s.startsWith(" Hello")ands.endsWith(" ")for position checks, ands.indexOf("o")to get the first index of a substring (returns -1 if not found).lastIndexOf()searches from the end. - Replace text. Run
s.replace("World", "There")to replace the first match. Uses.replaceAll("l", "L")to replace every occurrence. Both accept a string or a regular expression as the search pattern. - Split and join. Run
s.trim().split(", ")to get an array of parts. To turn an array back into a string, usearray.join(" "). Note thatsplit()returns an array, not a string. - Pad and repeat. Run
"7".padStart(3, "0")to get"007","7".padEnd(3, "0")to get"700", and"ab".repeat(3)to get"ababab". The pad length is the total target length, not the number of characters added. - Match with regular expressions. Run
s.match(/o/g)to get an array of all matches, ors.match(/o/)for the first match with extra details. Uses.search(/World/)for just the index of the first match. - Combine strings. Use the
+operator or template literals for most cases.concat()also works:"Hello".concat(", ", "World"). Template literals are usually clearer when mixing variables and text.
Common Mistakes
- Expecting methods to change the original string. Strings are immutable.
trim(),toUpperCase(),replace()and friends return a new string; you must assign the result:s = s.trim();. - Confusing
slice()andsubstring(). They behave differently with negative numbers and reversed arguments. Pick one and stick to it. - Forgetting that
lengthis a property. Writings.length()throws a TypeError. - Assuming
replace()replaces every match. Without a global regular expression orreplaceAll(), only the first occurrence changes. - Using
indexOf()as a boolean. It returns -1 when not found, which is truthy. Compare explicitly:if (s.indexOf("x") !== -1). - Mixing up
split()andjoin().split()is a string method that returns an array;join()is an array method that returns a string.
Tips
- Use template literals (
`Hello ${name}`) instead of concatenation when building strings from variables — it is easier to read and less error-prone. - Prefer
includes()overindexOf() !== -1for readability when you only need a true/false answer. - Remember that string indexes are zero-based: the first character is at index 0, not 1.
- When working with user input, trim first and then validate; leading or trailing spaces often cause unexpected mismatches.
- Use a global flag (
/pattern/g) withmatch()orreplace()when you need all occurrences.
Troubleshooting
If a method returns undefined, check that you are calling it on a string and not on null or undefined. If you get a TypeError about a function not existing, confirm the method name is spelled correctly and that you are not adding parentheses to a property like length. If replace() only changes the first match, add the global flag or switch to replaceAll(). If split() gives unexpected results, log the separator you passed — a space and a comma-space are different. When a regular expression does not match, test it in isolation with console.log(/pattern/.test(s)) to confirm the pattern itself works before combining it with other methods. Finally, if you are unsure what a method returns, log the result and its type with typeof; many string methods return arrays or numbers, not strings.
Frequently Asked Questions
What is the difference between slice() and substring()?
slice() accepts negative indexes (counting from the end) and returns an empty string if start is greater than end. substring() treats negative values as 0 and swaps the arguments if start is greater than end.
Does replace() change the original string?
No. Strings are immutable in JavaScript. replace() returns a new string; assign it to a variable to keep the change.
How do I check if a string contains a substring?
Use includes() for a true/false result, or indexOf() !== -1 if you also need the position. Both are case-sensitive.
Why does "abc".length return 3 but not always match the number of visible characters?
length counts UTF-16 code units. Characters outside the Basic Multilingual Plane, such as many emoji, use two code units, so the count can be higher than the number of visible characters.
Can I chain string methods?
Yes, as long as each method returns a string. For example, s.trim().toUpperCase().split(" ") works because trim() and toUpperCase() return strings, and split() returns an array at the end.
What is the difference between match() and search()?
match() returns an array of matches (or null), while search() returns the index of the first match (or -1). Use search() when you only need the position.