JS

Strings

JavaScript · 10 entries

Template Literals

syntax
`text ${expression} text`
example
const item = "coffee";
const price = 4.5;
console.log(`One ${item} costs $${price.toFixed(2)}.`);

const multiline = `Line one
Line two
Line three`;
console.log(multiline);
output
"One coffee costs $4.50."
"Line one\nLine two\nLine three"

Note Backtick strings support embedded expressions and multiline content without escape characters.

Tagged Templates

syntax
tagFunction`text ${expr} text`
example
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    return result + str + (values[i] !== undefined ? `[${values[i]}]` : "");
  }, "");
}
const user = "Kai";
console.log(highlight`Welcome, ${user}! You have ${3} alerts.`);
output
"Welcome, [Kai]! You have [3] alerts."

Note Tagged templates let you process template literal parts before producing the final string. Used in libraries like styled-components and GraphQL.

String Searching

syntax
str.includes(search, startIndex)
str.startsWith(search)
str.endsWith(search)
example
const msg = "Order #1234 shipped";
console.log(msg.includes("shipped"));   // true
console.log(msg.startsWith("Order"));   // true
console.log(msg.endsWith("shipped"));   // true
console.log(msg.indexOf("#"));          // 6

Note All search methods are case-sensitive. For case-insensitive checks, lowercase both sides first: str.toLowerCase().includes(term.toLowerCase()).

Extracting Substrings

syntax
str.slice(start, end)
str.substring(start, end)
example
const path = "/users/profile/avatar.png";
console.log(path.slice(1));          // "users/profile/avatar.png"
console.log(path.slice(-10));        // "avatar.png"
console.log(path.slice(7, 14));      // "profile"

Note slice() supports negative indices (counts from end). substring() does not. Prefer slice() -- it is more predictable.

Replacing Text

syntax
str.replace(search, replacement)
str.replaceAll(search, replacement)
example
const template = "Hello {name}, welcome to {place}!";
const filled = template
  .replace("{name}", "Ava")
  .replace("{place}", "Berlin");
console.log(filled);

const csv = "a,b,c,d";
console.log(csv.replaceAll(",", " | "));
output
"Hello Ava, welcome to Berlin!"
"a | b | c | d"

Note replace() only swaps the first match unless you use a regex with the /g flag. replaceAll() replaces every occurrence.

Split and Join

syntax
str.split(separator, limit)
arr.join(separator)
example
const tags = "js,react,node";
const tagArray = tags.split(",");
console.log(tagArray);
console.log(tagArray.join(" + "));
output
["js", "react", "node"]
"js + react + node"

Note split("") splits into individual characters. split() with no arguments returns the entire string in a single-element array.

Trimming Whitespace

syntax
str.trim()
str.trimStart()
str.trimEnd()
example
const input = "  [email protected]  ";
console.log(input.trim());       // "[email protected]"
console.log(input.trimStart());  // "[email protected]  "
console.log(input.trimEnd());    // "  [email protected]"

Note Essential for cleaning user input. Only removes whitespace characters (spaces, tabs, newlines), not other invisible characters.

Padding Strings

syntax
str.padStart(targetLength, padChar)
str.padEnd(targetLength, padChar)
example
const orderNum = "42";
console.log(orderNum.padStart(6, "0"));  // "000042"

const label = "Price";
console.log(label.padEnd(12, "."));      // "Price......."

Note Useful for formatting IDs, aligning columns in console output, or zero-padding numbers.

Case Conversion

syntax
str.toUpperCase()
str.toLowerCase()
str.toLocaleUpperCase(locale)
example
const status = "Pending";
console.log(status.toUpperCase());  // "PENDING"
console.log(status.toLowerCase());  // "pending"

// Locale-aware (e.g., Turkish "i" -> "I" with dot)
console.log("istanbul".toLocaleUpperCase("tr"));

Note Always use locale-aware methods when dealing with internationalized text. The Turkish i is a classic bug source.

Repeat and Character Access

syntax
str.repeat(count)
str.at(index)
example
const border = "=".repeat(30);
console.log(border);

const word = "JavaScript";
console.log(word.at(0));   // "J"
console.log(word.at(-1));  // "t"

Note at() supports negative indices to count from the end. Bracket notation str[-1] returns undefined, not the last character.