JavaScript BasicsFeatured

JavaScript String Methods: Complete Reference Guide

Master all JavaScript string methods with practical examples. Learn string manipulation, searching, transformation, and modern string handling techniques.

By JavaScript Document Team
stringsmethodsbasicsreferencemanipulation

Strings are one of the most commonly used data types in JavaScript. Understanding string methods is essential for text processing, data manipulation, and building user interfaces. This comprehensive guide covers all JavaScript string methods with practical examples.

String Creation and Basics

Creating Strings

// String literals
const str1 = 'Hello World';
const str2 = 'Hello World';
const str3 = `Hello World`; // Template literal

// String constructor
const str4 = new String('Hello World'); // String object
const str5 = String('Hello World'); // String primitive

// String from other types
const str6 = String(123); // "123"
const str7 = String(true); // "true"
const str8 = String(null); // "null"
const str9 = String(undefined); // "undefined"

// Template literals with expressions
const name = 'John';
const greeting = `Hello, ${name}!`; // "Hello, John!"

String Properties

length

const str = 'Hello World';
console.log(str.length); // 11

// Unicode characters
const emoji = '😀';
console.log(emoji.length); // 2 (because it's a surrogate pair)

// Correct way to count Unicode characters
console.log([...emoji].length); // 1
console.log(Array.from(emoji).length); // 1

Accessing Characters

charAt() and charCodeAt()

const str = 'JavaScript';

// charAt() - returns character at index
console.log(str.charAt(0)); // "J"
console.log(str.charAt(4)); // "S"
console.log(str.charAt(20)); // "" (empty string for out of bounds)

// charCodeAt() - returns Unicode value
console.log(str.charCodeAt(0)); // 74 (Unicode for 'J')
console.log(str.charCodeAt(4)); // 83 (Unicode for 'S')
console.log(str.charCodeAt(20)); // NaN (out of bounds)

// Using bracket notation
console.log(str[0]); // "J"
console.log(str[4]); // "S"
console.log(str[20]); // undefined

codePointAt()

// For Unicode characters beyond BMP
const str = '𝒜BC'; // Mathematical bold A

console.log(str.codePointAt(0)); // 119964 (code point for 𝒜)
console.log(str.charCodeAt(0)); // 55349 (only first surrogate)

// Iterating over code points
for (let codePoint of str) {
  console.log(codePoint, codePoint.codePointAt(0));
}

String Search Methods

indexOf() and lastIndexOf()

const str = 'Hello World, Hello Universe';

// indexOf() - first occurrence
console.log(str.indexOf('Hello')); // 0
console.log(str.indexOf('World')); // 6
console.log(str.indexOf('hello')); // -1 (case sensitive)
console.log(str.indexOf('o')); // 4

// With start position
console.log(str.indexOf('Hello', 1)); // 13
console.log(str.indexOf('o', 5)); // 7

// lastIndexOf() - last occurrence
console.log(str.lastIndexOf('Hello')); // 13
console.log(str.lastIndexOf('o')); // 19

// With start position (searches backwards)
console.log(str.lastIndexOf('o', 18)); // 16

includes()

const str = 'JavaScript is awesome';

console.log(str.includes('Script')); // true
console.log(str.includes('script')); // false (case sensitive)
console.log(str.includes('Python')); // false

// With position parameter
console.log(str.includes('is', 11)); // true
console.log(str.includes('Java', 5)); // false

startsWith() and endsWith()

const str = 'JavaScript Programming';

// startsWith()
console.log(str.startsWith('Java')); // true
console.log(str.startsWith('Script')); // false
console.log(str.startsWith('Script', 4)); // true (starts check at index 4)

// endsWith()
console.log(str.endsWith('ming')); // true
console.log(str.endsWith('Program')); // false
console.log(str.endsWith('Script', 10)); // true (checks first 10 characters)

search()

const str = 'The quick brown fox jumps';

// search() uses regular expressions
console.log(str.search('quick')); // 4
console.log(str.search(/quick/)); // 4
console.log(str.search(/Quick/i)); // 4 (case insensitive)
console.log(str.search(/\bfox\b/)); // 16 (word boundary)
console.log(str.search(/xyz/)); // -1

match() and matchAll()

const str = 'The price is $10.99 and tax is $2.50';

// match() with string
console.log(str.match('$')); // null ($ is special in regex)

// match() with regex
console.log(str.match(/\$\d+\.\d{2}/)); // ["$10.99", index: 13, ...]
console.log(str.match(/\$\d+\.\d{2}/g)); // ["$10.99", "$2.50"]

// matchAll() - returns iterator
const matches = str.matchAll(/\$(\d+)\.(\d{2})/g);
for (const match of matches) {
  console.log(`Found ${match[0]}: dollars=${match[1]}, cents=${match[2]}`);
}
// Found $10.99: dollars=10, cents=99
// Found $2.50: dollars=2, cents=50

String Extraction Methods

slice()

const str = 'JavaScript Programming';

// slice(start, end)
console.log(str.slice(0, 10)); // "JavaScript"
console.log(str.slice(11)); // "Programming"
console.log(str.slice(-11)); // "Programming"
console.log(str.slice(4, -8)); // "Script"

// Negative indices
console.log(str.slice(-11, -1)); // "Programmin"
console.log(str.slice(-1)); // "g"

// If start > end, returns empty string
console.log(str.slice(10, 4)); // ""

substring()

const str = 'JavaScript Programming';

// substring(start, end)
console.log(str.substring(0, 10)); // "JavaScript"
console.log(str.substring(11)); // "Programming"

// Differences from slice:
// 1. Negative values are treated as 0
console.log(str.substring(-5)); // "JavaScript Programming"
console.log(str.substring(0, -5)); // ""

// 2. If start > end, they are swapped
console.log(str.substring(10, 4)); // "Script"

substr() (Deprecated)

const str = 'JavaScript Programming';

// substr(start, length)
console.log(str.substr(0, 10)); // "JavaScript"
console.log(str.substr(11)); // "Programming"
console.log(str.substr(-11, 7)); // "Program"

// Note: substr() is deprecated, use slice() or substring() instead

String Transformation Methods

toLowerCase() and toUpperCase()

const str = 'JavaScript Programming';

console.log(str.toLowerCase()); // "javascript programming"
console.log(str.toUpperCase()); // "JAVASCRIPT PROGRAMMING"

// Locale-specific transformations
const turkish = 'İstanbul';
console.log(turkish.toLowerCase()); // "i̇stanbul"
console.log(turkish.toLocaleLowerCase('tr-TR')); // "istanbul"

trim(), trimStart(), and trimEnd()

const str = '  Hello World  \n\t';

console.log(str.trim()); // "Hello World"
console.log(str.trimStart()); // "Hello World  \n\t"
console.log(str.trimEnd()); // "  Hello World"

// Legacy aliases
console.log(str.trimLeft()); // Same as trimStart()
console.log(str.trimRight()); // Same as trimEnd()

// Removes all whitespace characters
const messy = '\n\t  Content \r\n  ';
console.log(messy.trim()); // "Content"

replace() and replaceAll()

const str = 'Hello World, Hello Universe';

// replace() - replaces first occurrence
console.log(str.replace('Hello', 'Hi')); // "Hi World, Hello Universe"
console.log(str.replace(/Hello/g, 'Hi')); // "Hi World, Hi Universe"

// Using function as replacement
console.log(
  str.replace(/Hello/g, (match, offset) => {
    return offset === 0 ? 'Hi' : 'Hey';
  })
); // "Hi World, Hey Universe"

// replaceAll() - replaces all occurrences
console.log(str.replaceAll('Hello', 'Hi')); // "Hi World, Hi Universe"

// Capturing groups
const price = 'Price: $10.99';
console.log(price.replace(/\$(\d+)\.(\d+)/, '$$$2.$1')); // "Price: $99.10"

split()

const str = 'apple,banana,orange';

// Split by delimiter
console.log(str.split(',')); // ["apple", "banana", "orange"]
console.log(str.split(',', 2)); // ["apple", "banana"] (limit)

// Split by regex
const mixed = 'apple1banana2orange3';
console.log(mixed.split(/\d/)); // ["apple", "banana", "orange", ""]

// Split into characters
console.log('Hello'.split('')); // ["H", "e", "l", "l", "o"]

// Split with capturing groups
const data = 'a=1&b=2&c=3';
console.log(data.split(/(&)/)); // ["a=1", "&", "b=2", "&", "c=3"]

String Concatenation and Repetition

concat()

const str1 = 'Hello';
const str2 = ' ';
const str3 = 'World';

console.log(str1.concat(str2, str3)); // "Hello World"
console.log(str1.concat(' ', 'World', '!')); // "Hello World!"

// Using + operator is more common
console.log(str1 + str2 + str3); // "Hello World"

// Template literals are most readable
console.log(`${str1}${str2}${str3}`); // "Hello World"

repeat()

const str = 'Ha';

console.log(str.repeat(3)); // "HaHaHa"
console.log('*'.repeat(10)); // "**********"
console.log('=-'.repeat(5)); // "=-=-=-=-=-"

// Practical use cases
const indent = ' '.repeat(4); // 4 spaces for indentation
const line = '-'.repeat(50); // Separator line

// Error cases
// console.log(str.repeat(-1));      // RangeError
// console.log(str.repeat(Infinity)); // RangeError

String Padding

padStart() and padEnd()

// padStart()
console.log('5'.padStart(3, '0')); // "005"
console.log('123'.padStart(5, '0')); // "00123"
console.log('abc'.padStart(6, '123')); // "123abc"
console.log('abc'.padStart(2)); // "abc" (no padding needed)

// padEnd()
console.log('5'.padEnd(3, '0')); // "500"
console.log('123'.padEnd(5, '0')); // "12300"
console.log('abc'.padEnd(6, '123')); // "abc123"

// Practical examples
const formatTime = (hours, minutes) => {
  return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
};

console.log(formatTime(9, 5)); // "09:05"
console.log(formatTime(10, 30)); // "10:30"

// Table formatting
const data = [
  ['Name', 'Age', 'City'],
  ['John', '25', 'NYC'],
  ['Alice', '30', 'LA'],
];

data.forEach((row) => {
  console.log(row[0].padEnd(10) + row[1].padEnd(5) + row[2]);
});

String Comparison

localeCompare()

// Basic comparison
console.log('a'.localeCompare('b')); // -1 (a comes before b)
console.log('b'.localeCompare('a')); // 1 (b comes after a)
console.log('a'.localeCompare('a')); // 0 (equal)

// Locale-aware sorting
const words = ['réservé', 'reserve', 'café', 'caffe'];
words.sort((a, b) => a.localeCompare(b, 'en'));
console.log(words); // ["café", "caffe", "reserve", "réservé"]

// Numeric comparison
const versions = ['item2', 'item10', 'item1', 'item20'];
versions.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
console.log(versions); // ["item1", "item2", "item10", "item20"]

// Case sensitivity
console.log('a'.localeCompare('A', undefined, { sensitivity: 'base' })); // 0

Modern String Methods

String.raw

// Template tag for raw strings
const path = String.raw`C:\Users\Documents\file.txt`;
console.log(path); // C:\Users\Documents\file.txt

// With template literal
const name = 'John';
const raw = String.raw`Hello\n${name}`;
console.log(raw); // Hello\nJohn (literal \n, not newline)

// Custom template tag
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    const value = values[i - 1];
    return result + (value ? `<mark>${value}</mark>` : '') + str;
  });
}

const highlighted = highlight`Hello ${name}, welcome!`;
console.log(highlighted); // Hello <mark>John</mark>, welcome!

String.fromCharCode() and String.fromCodePoint()

// fromCharCode() - creates string from Unicode values
console.log(String.fromCharCode(72, 101, 108, 108, 111)); // "Hello"
console.log(String.fromCharCode(0x1f600)); // Incorrect for emoji

// fromCodePoint() - handles full Unicode range
console.log(String.fromCodePoint(0x1f600)); // "😀"
console.log(String.fromCodePoint(0x1f1fa, 0x1f1f8)); // "🇺🇸"

// Creating alphabet
const alphabet = Array.from({ length: 26 }, (_, i) =>
  String.fromCharCode(65 + i)
).join('');
console.log(alphabet); // "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

Practical Examples

Email Validation

function isValidEmail(email) {
  return email.toLowerCase().match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/) !== null;
}

console.log(isValidEmail('user@example.com')); // true
console.log(isValidEmail('invalid.email')); // false

Title Case Conversion

function toTitleCase(str) {
  return str.replace(/\b\w/g, (char) => char.toUpperCase());
}

console.log(toTitleCase('hello world from javascript'));
// "Hello World From Javascript"

// More sophisticated version
function properTitleCase(str) {
  const exceptions = ['a', 'an', 'the', 'in', 'on', 'at', 'to', 'for'];

  return str.toLowerCase().replace(/\b\w+/g, (word, index) => {
    if (index === 0 || !exceptions.includes(word)) {
      return word.charAt(0).toUpperCase() + word.slice(1);
    }
    return word;
  });
}

console.log(properTitleCase('the quick brown fox in the woods'));
// "The Quick Brown Fox in the Woods"

URL Slug Generation

function createSlug(title) {
  return title
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '') // Remove special characters
    .replace(/\s+/g, '-') // Replace spaces with hyphens
    .replace(/--+/g, '-') // Replace multiple hyphens
    .replace(/^-+|-+$/g, ''); // Trim hyphens from ends
}

console.log(createSlug('Hello World! How are you?'));
// "hello-world-how-are-you"

console.log(createSlug('  JavaScript -- The   Best Language!  '));
// "javascript-the-best-language"

Word Count and Statistics

function getTextStats(text) {
  const words = text
    .trim()
    .split(/\s+/)
    .filter((word) => word.length > 0);
  const characters = text.replace(/\s/g, '').length;
  const sentences = text
    .split(/[.!?]+/)
    .filter((s) => s.trim().length > 0).length;

  return {
    words: words.length,
    characters: characters,
    charactersWithSpaces: text.length,
    sentences: sentences,
    averageWordLength: (characters / words.length).toFixed(2),
  };
}

const text = 'Hello world. This is a test! How are you?';
console.log(getTextStats(text));
// { words: 9, characters: 32, charactersWithSpaces: 42, sentences: 3, averageWordLength: "3.56" }

Performance Tips

  1. String concatenation: Use template literals for readability
  2. Repeated operations: Cache results when possible
  3. Large strings: Consider using arrays and join() for multiple concatenations
  4. Regular expressions: Compile once and reuse for better performance
  5. Unicode handling: Use appropriate methods for full Unicode support

Conclusion

JavaScript provides a rich set of string methods for every text manipulation need. Understanding these methods and when to use them is crucial for effective JavaScript programming. Remember that strings are immutable in JavaScript, so all string methods return new strings rather than modifying the original.