Comprehensive Guide to JavaScript String Methods

Character Access

The charAt() method retrieves the character at a specific index position. Modern JavaScript also supports bracket notation for the same purpose.

const text = 'developer';

console.log(text.charAt(0)); // 'd'
console.log(text[0]);        // 'd' (equivalent)

// charCodeAt() returns the Unicode code point
console.log(text.charCodeAt(0)); // 100

Extracting Substrings

slice() extracts a portion of a string and returns it as a new string. It accepts start and end indices, with negative values counting from the end.

const message = 'frontend';

console.log(message.slice(0, 5));   // 'front'
console.log(message.slice(3));     // 'tend'
console.log(message.slice(-4, -1)); // 'ten'

substring() behaves similarly but automatically swaps arguments if the second is smaller than the first, and treats negative values as zero.

const word = 'javascript';

console.log(word.substring(0, 4));  // 'java'
console.log(word.substring(4, 0));  // 'java' (swapped automatically)
console.log(word.substring(-2, 4)); // 'java' (negative becomes 0)

String Concatenation

concat() joins multiple strings together. Non-string values are automatically converted.

const result = 'Java'.concat('Script', ' ', 'ES6');
console.log(result); // 'JavaScript ES6'

const nums = ''.concat(2024, '-', 12);
console.log(nums); // '2024-12'

Splitting Strings

split() divides a string into an array of substrings based on a separator.

const csv = 'apple,banana,cherry';

console.log(csv.split(','));    // ['apple', 'banana', 'cherry']
console.log('abc'.split(''));   // ['a', 'b', 'c']
console.log(csv.split());       // ['apple,banana,cherry']

Searching Within Strings

indexOf() and lastIndexOf() locate the position of a substring, returning -1 if not found.

const phrase = 'programming';

console.log(phrase.indexOf('m'));     // 6
console.log(phrase.lastIndexOf('m')); // 7

search() executes a search for a match and returns the index of the first match.

const sentence = 'Hello World';
console.log(sentence.search('World')); // 6
console.log(sentence.search(/world/i)); // 6 (case-insensitive regex)

Pattern Matching

match() retrieves the result of matching a string against a regular expression.

const data = 'cat, bat, rat, hat';
const matches = data.match(/[cr]at/g);

console.log(matches); // ['cat', 'rat']

// Without global flag, returns detailed match info
const singleMatch = data.match('bat');
console.log(singleMatch.index); // 5
console.log(singleMatch.input); // 'cat, bat, rat, hat'

String Replacement

replace() returns a new string with some or all matches replaced. Without regex, only the first occurrence is replaced.

const greeting = 'hello world, hello universe';

console.log(greeting.replace('hello', 'hi'));
// 'hi world, hello universe'

// Using regex with global flag to replace all
console.log(greeting.replace(/hello/g, 'hi'));
// 'hi world, hi universe'

Trimming Whitespace

trim() removes whitespace from both ends of a string.

const padded = '   hello world   ';
console.log(padded.trim()); // 'hello world'

Case Conversion

const lower = 'javascript';
console.log(lower.toUpperCase()); // 'JAVASCRIPT'

const upper = 'TYPESCRIPT';
console.log(upper.toLowerCase()); // 'typescript'

ES6+ String Enhancements

Iterating Over Strings

Strings now implement the iterator interface, making them directly iterable with for...of loops.

const chars = 'ABC';

for (const char of chars) {
    console.log(char);
}
// 'A', 'B', 'C'

Template Literals

Template literals provide powerful string formatting capabilities with embedded expressions.

const name = 'Alice';
const age = 30;

// Multi-line strings and variable interpolation
const intro = `User Profile:
Name: ${name}
Age: ${age}
Next Year: ${age + 1}`;

console.log(intro);

// Template compilation example
const items = ['Apple', 'Banana', 'Cherry'];
const list = `
<ul>
  ${items.map(item => `<li>${item}</li>`).join('\n  ')}
</ul>`;

Substring Detection Methods

ES6 introduced methods that return boolean values for substring checking.

const url = 'https://example.com/docs';

console.log(url.startsWith('https'));  // true
console.log(url.endsWith('docs'));     // true
console.log(url.includes('example'));  // true

String Repetition

repeat() constructs and returns a new string containing the specified number of copies.

console.log('ab'.repeat(3));    // 'ababab'
console.log('*'.repeat(5));      // '*****'

String Padding

padStart() and padEnd() pad the current string with another string until the resulting string reaches the given length.

const num = '5';

console.log(num.padStart(3, '0'));  // '005'
console.log(num.padEnd(3, '0'));    // '500'

// Practical example: formatting dates
const day = '7'.padStart(2, '0');
const month = '12'.padStart(2, '0');
console.log(`${month}/${day}`); // '12/07'

Targeted Trimming

ES2019 added methods to trim whitespace from specific ends of a string.

const text = '   content   ';

console.log(text.trimStart()); // 'content   '
console.log(text.trimEnd());   // '   content'

Replace All Occurrences

replaceAll() replaces all instances of a pattern without requiring a regex with the global flag.

const sentence = 'the cat sat on the mat';

console.log(sentence.replaceAll('the', 'a'));
// 'a cat sat on a mat'

// With regex, the 'g' flag is mandatory
console.log(sentence.replaceAll(/at/g, 'op'));
// 'the cop sat on the mop'

Match All Iterations

matchAll() returns an iterator of all results matching a global regular expression, providing detailed match information for each occurrence.

const text = 'test1test2test3';
const matches = [...text.matchAll(/test(\d)/g)];

for (const match of matches) {
    console.log(`Found: ${match[0]} at index ${match.index}`);
}
// Found: test1 at index 0
// Found: test2 at index 5
// Found: test3 at index 10

Tags: javascript String Methods ES6 Template Literals

Posted on Sun, 14 Jun 2026 17:52:59 +0000 by jpraj