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.

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.