JavaScript Strings
Slice, search, replace, split, and pad strings, and build them with template literal interpolation.
TL;DR
- Use
slice()andsubstring()to extract portions of strings. - Use
replace()andreplaceAll()to substitute text inside strings. - Use
split()andjoin()to convert between strings and arrays.
Extracting Substrings
slice()Extracts a section of a string and returns it as a new string.
const text = "Hello World";
const res = text.slice(0, 5); // "Hello"
const word = text.slice(-5); // "World"substring()Extracts characters between two indices, treating negative index numbers as zero.
const text = "Hello";
const res = text.substring(1, 4); // "ell"substr()Extracts a substring starting at an index for a specified character length.
const text = "Hello";
const res = text.substr(1, 3); // "ell"Finding and Checking
indexOf()Returns the index of the first occurrence of a specified substring.
const text = "hello world";
text.indexOf("world"); // 6
text.indexOf("xyz"); // -1includes()Performs a case-sensitive search to determine if a substring exists.
const text = "hello world";
text.includes("world"); // truestartsWith()Checks if a string begins with the characters of a specified string.
const text = "hello";
text.startsWith("he"); // truesearch()Executes a regular expression search and returns the first matching index.
const text = "hello123";
text.search(/\d+/); // 5Replace and Transform
replace()Replaces the first match of a substring or regular expression pattern.
const text = "hello world";
text.replace("world", "there"); // "hello there"replaceAll()Replaces all occurrences of a literal substring or global regex pattern.
const text = "hello hello";
text.replaceAll("hello", "hi"); // "hi hi"Case conversionTransforms all characters in a string to uppercase or lowercase forms.
const text = "Hello";
text.toUpperCase(); // "HELLO"
text.toLowerCase(); // "hello"Replace callbackUses a replacement function to compute custom replacements for each match.
const text = "hello world";
const title = text.replace(
/\b\w/g,
ch => ch.toUpperCase()
);
// "Hello World"Split and Join & Trimming and Padding
split()Splits a string into an array of substrings using a separator.
"a,b,c".split(","); // ["a","b","c"]join()Joins array elements into a single string with a separator.
["a","b","c"].join(","); // "a,b,c"split limitTruncates the result to a max number of elements.
"a,b,c,d".split(",", 2); // ["a","b"]regex splitSplits using a regex to match multiple separators.
"one, two; three".split(/[,;]\s*/);trim()Removes whitespace from both ends of a string.
" hello ".trim(); // "hello"trimStart()Removes whitespace from the start of a string only.
" hello".trimStart(); // "hello"padStart()Pads the string from the start with a fill character.
"5".padStart(3, "0"); // "005"repeat()Copies the string N times.
"-".repeat(10); // "----------"String Interpolation
${} syntaxInserts variables directly into strings without using the concatenation plus operator.
const name = "Alice";
const greeting = `Hello, ${name}!`;ExpressionsEvaluates any valid JavaScript expressions inside the interpolation curly braces.
const a = 5, b = 10;
const sum = `${a} + ${b} = ${a + b}`;Tips
- Use
includes()instead ofindexOf() !== -1to write cleaner, more readable boolean search checks on strings. - Use
localeCompare()instead of comparison operators when sorting strings containing accented characters to ensure correct alphabetical ordering.
Warnings
- Avoid using the deprecated
substr()method because it is not supported in some modern environments and libraries. - Remember that JavaScript strings are immutable, meaning methods like
trim()andreplace()always return new string values.
In Practice
Cleans up messy text inputs by trimming excess whitespace and capitalizing the first letter of each name word.
- Trim leading and trailing whitespace from the raw user input.
- Split the cleaned string into an array of individual words.
- Map over each word to isolate and capitalize its first character.
- Convert the remaining characters of each word to lowercase form.
- Rejoin the capitalized words back into a single space-separated string.
function cleanName(rawName) {
const trimmed = rawName.trim();
if (!trimmed) return "";
const words = trimmed.split(/\s+/);
const capitalized = words.map(w => {
const first = w[0].toUpperCase();
const rest = w.slice(1).toLowerCase();
return first + rest;
});
return capitalized.join(" ");
}FAQ
Both methods extract parts of strings using start and end indices. However, slice() supports negative indices to count from the end of the string. The substring() method treats negative values as zero. Prefer slice() for its flexibility.
Use replaceAll('old', 'new') to replace every match of a literal substring. Alternatively, use a regular expression with the global flag like replace(/pattern/g, 'new'). The standard replace() method only replaces the first occurrence.
Use padStart(targetLength, padChar) to insert characters from the left. For example, '7'.padStart(3, '0') outputs '007'. To pad from the right, use padEnd() instead.
Yes, template literals preserve actual line breaks. Pressing Enter inside backticks creates a real newline in the string. You do not need to use \n escape sequences anymore.