String Methods: Complete Reference in JavaScript
Introduction
Strings are fundamental data types in JavaScript, and mastering string methods is essential for effective programming. JavaScript provides a comprehensive set of built-in string methods for searching, transforming, and manipulating text. In this article, you’ll learn all major string methods with practical examples and use cases.
String Creation and Properties
Creating Strings
// String literals
const str1 = 'Hello';
const str2 = "World";
const str3 = `Template ${str1}`;
// String constructor
const str4 = new String('Hello');
// String properties
const str = 'Hello';
console.log(str.length); // 5
console.log(str[0]); // 'H'
console.log(str.charAt(0)); // 'H'
Character Access Methods
charAt()
// Get character at specific index
const str = 'Hello';
console.log(str.charAt(0)); // 'H'
console.log(str.charAt(1)); // 'e'
console.log(str.charAt(10)); // '' (empty string)
// Practical example: Get first character
function getFirstChar(str) {
return str.charAt(0);
}
console.log(getFirstChar('JavaScript')); // 'J'
charCodeAt()
// Get character code at specific index
const str = 'Hello';
console.log(str.charCodeAt(0)); // 72 (H)
console.log(str.charCodeAt(1)); // 101 (e)
// Practical example: Check if character is uppercase
function isUpperCase(char) {
return char.charCodeAt(0) >= 65 && char.charCodeAt(0) <= 90;
}
console.log(isUpperCase('A')); // true
console.log(isUpperCase('a')); // false
codePointAt()
// Get Unicode code point (handles emoji)
const str = 'Hello ๐';
console.log(str.codePointAt(0)); // 72 (H)
console.log(str.codePointAt(6)); // 128512 (๐)
// Practical example: Handle emoji
function getEmoji(str) {
return str.codePointAt(0) > 127 ? str[0] : null;
}
Case Conversion Methods
toUpperCase() and toLowerCase()
// Convert case
const str = 'Hello World';
console.log(str.toUpperCase()); // 'HELLO WORLD'
console.log(str.toLowerCase()); // 'hello world'
// Practical example: Case-insensitive comparison
function compareIgnoreCase(str1, str2) {
return str1.toLowerCase() === str2.toLowerCase();
}
console.log(compareIgnoreCase('Hello', 'HELLO')); // true
toLocaleUpperCase() and toLocaleLowerCase()
// Locale-aware case conversion
const str = 'istanbul';
console.log(str.toLocaleUpperCase('tr-TR')); // 'ฤฐSTANBUL' (Turkish)
console.log(str.toLocaleUpperCase('en-US')); // 'ISTANBUL' (English)
Searching Methods
indexOf()
// Find first occurrence
const str = 'Hello World Hello';
console.log(str.indexOf('o')); // 4
console.log(str.indexOf('World')); // 6
console.log(str.indexOf('xyz')); // -1 (not found)
console.log(str.indexOf('o', 5)); // 7 (start from index 5)
// Practical example: Check if string contains substring
function contains(str, substring) {
return str.indexOf(substring) !== -1;
}
console.log(contains('Hello World', 'World')); // true
lastIndexOf()
// Find last occurrence
const str = 'Hello World Hello';
console.log(str.lastIndexOf('o')); // 15
console.log(str.lastIndexOf('Hello')); // 12
console.log(str.lastIndexOf('xyz')); // -1
// Practical example: Get last word
function getLastWord(str) {
const lastSpace = str.lastIndexOf(' ');
return lastSpace === -1 ? str : str.substring(lastSpace + 1);
}
console.log(getLastWord('Hello World')); // 'World'
includes()
// Check if string contains substring
const str = 'Hello World';
console.log(str.includes('World')); // true
console.log(str.includes('xyz')); // false
console.log(str.includes('o', 5)); // true (start from index 5)
// Practical example: Validate email
function isValidEmail(email) {
return email.includes('@') && email.includes('.');
}
console.log(isValidEmail('[email protected]')); // true
startsWith() and endsWith()
// Check string start and end
const str = 'Hello World';
console.log(str.startsWith('Hello')); // true
console.log(str.startsWith('World')); // false
console.log(str.endsWith('World')); // true
console.log(str.endsWith('Hello')); // false
// Practical example: File type validation
function isImageFile(filename) {
const imageExtensions = ['.jpg', '.png', '.gif', '.webp'];
return imageExtensions.some(ext => filename.toLowerCase().endsWith(ext));
}
console.log(isImageFile('photo.jpg')); // true
console.log(isImageFile('document.pdf')); // false
search()
// Search using regex
const str = 'Hello World 123';
console.log(str.search(/\d+/)); // 12 (first digit)
console.log(str.search(/xyz/)); // -1 (not found)
// Practical example: Find first number
function findFirstNumber(str) {
const index = str.search(/\d/);
return index !== -1 ? str[index] : null;
}
console.log(findFirstNumber('abc123def')); // '1'
Extraction Methods
substring()
// Extract substring
const str = 'Hello World';
console.log(str.substring(0, 5)); // 'Hello'
console.log(str.substring(6)); // 'World'
console.log(str.substring(6, 11)); // 'World'
console.log(str.substring(11, 6)); // 'World' (swaps if reversed)
// Practical example: Get domain from email
function getDomain(email) {
const atIndex = email.indexOf('@');
return email.substring(atIndex + 1);
}
console.log(getDomain('[email protected]')); // 'example.com'
substr()
// Extract substring (deprecated, use substring or slice)
const str = 'Hello World';
console.log(str.substr(0, 5)); // 'Hello'
console.log(str.substr(6)); // 'World'
console.log(str.substr(-5)); // 'World' (from end)
// Note: substr is deprecated, use slice instead
slice()
// Extract substring (modern approach)
const str = 'Hello World';
console.log(str.slice(0, 5)); // 'Hello'
console.log(str.slice(6)); // 'World'
console.log(str.slice(-5)); // 'World' (from end)
console.log(str.slice(-5, -1)); // 'Worl'
// Practical example: Get file extension
function getFileExtension(filename) {
const lastDot = filename.lastIndexOf('.');
return lastDot === -1 ? '' : filename.slice(lastDot + 1);
}
console.log(getFileExtension('document.pdf')); // 'pdf'
Transformation Methods
split()
// Split string into array
const str = 'Hello World JavaScript';
console.log(str.split(' ')); // ['Hello', 'World', 'JavaScript']
console.log(str.split('')); // ['H', 'e', 'l', 'l', 'o', ...]
console.log(str.split(' ', 2)); // ['Hello', 'World']
// Practical example: Parse CSV
function parseCSV(csv) {
return csv.split(',').map(item => item.trim());
}
console.log(parseCSV('apple, banana, orange')); // ['apple', 'banana', 'orange']
replace()
// Replace first occurrence
const str = 'Hello World Hello';
console.log(str.replace('Hello', 'Hi')); // 'Hi World Hello'
console.log(str.replace(/Hello/g, 'Hi')); // 'Hi World Hi'
// Practical example: Sanitize input
function sanitizeHTML(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
console.log(sanitizeHTML('<script>alert("xss")</script>'));
replaceAll()
// Replace all occurrences
const str = 'Hello World Hello';
console.log(str.replaceAll('Hello', 'Hi')); // 'Hi World Hi'
console.log(str.replaceAll(/o/g, '0')); // 'Hell0 W0rld Hell0'
// Practical example: Template replacement
function replaceTemplate(template, values) {
let result = template;
for (const [key, value] of Object.entries(values)) {
result = result.replaceAll(`{{${key}}}`, value);
}
return result;
}
const template = 'Hello {{name}}, welcome to {{place}}';
console.log(replaceTemplate(template, { name: 'John', place: 'Earth' }));
// 'Hello John, welcome to Earth'
trim(), trimStart(), trimEnd()
// Remove whitespace
const str = ' Hello World ';
console.log(str.trim()); // 'Hello World'
console.log(str.trimStart()); // 'Hello World '
console.log(str.trimEnd()); // ' Hello World'
// Practical example: Clean user input
function cleanInput(input) {
return input.trim().replace(/\s+/g, ' ');
}
console.log(cleanInput(' Hello World ')); // 'Hello World'
padStart() and padEnd()
// Pad string to length
const str = '5';
console.log(str.padStart(3, '0')); // '005'
console.log(str.padEnd(3, '0')); // '500'
// Practical example: Format numbers
function formatNumber(num, digits = 2) {
return String(num).padStart(digits, '0');
}
console.log(formatNumber(5)); // '05'
console.log(formatNumber(42, 3)); // '042'
repeat()
// Repeat string
const str = 'ab';
console.log(str.repeat(3)); // 'ababab'
console.log(str.repeat(0)); // ''
// Practical example: Create separator
function createSeparator(char = '-', length = 20) {
return char.repeat(length);
}
console.log(createSeparator()); // '--------------------'
console.log(createSeparator('=', 10)); // '=========='
concat()
// Concatenate strings
const str1 = 'Hello';
const str2 = 'World';
console.log(str1.concat(' ', str2)); // 'Hello World'
console.log(str1.concat(' ', str2, '!')); // 'Hello World!'
// Note: Use + or template literals instead
console.log(str1 + ' ' + str2); // 'Hello World'
console.log(`${str1} ${str2}`); // 'Hello World'
Matching Methods
match()
// Match using regex
const str = 'The price is $100 and $200';
console.log(str.match(/\$\d+/)); // ['$100']
console.log(str.match(/\$\d+/g)); // ['$100', '$200']
// Practical example: Extract numbers
function extractNumbers(str) {
const matches = str.match(/\d+/g);
return matches ? matches.map(Number) : [];
}
console.log(extractNumbers('I have 2 apples and 5 oranges')); // [2, 5]
matchAll()
// Match all with groups
const str = 'apple123banana456';
const regex = /([a-z]+)(\d+)/g;
for (const match of str.matchAll(regex)) {
console.log(match[0]); // Full match
console.log(match[1]); // First group
console.log(match[2]); // Second group
}
// Practical example: Parse key-value pairs
function parseKeyValues(str) {
const regex = /(\w+)=(\w+)/g;
const result = {};
for (const match of str.matchAll(regex)) {
result[match[1]] = match[2];
}
return result;
}
console.log(parseKeyValues('name=John&age=30&city=NYC'));
// { name: 'John', age: '30', city: 'NYC' }
Comparison Methods
localeCompare()
// Compare strings with locale awareness
const str1 = 'apple';
const str2 = 'banana';
console.log(str1.localeCompare(str2)); // -1 (str1 < str2)
console.log(str2.localeCompare(str1)); // 1 (str2 > str1)
console.log(str1.localeCompare(str1)); // 0 (equal)
// Practical example: Sort strings
function sortStrings(arr) {
return arr.sort((a, b) => a.localeCompare(b));
}
console.log(sortStrings(['zebra', 'apple', 'banana']));
// ['apple', 'banana', 'zebra']
Real-World Examples
Example 1: URL Slug Generator
// Generate URL-friendly slug
function generateSlug(text) {
return text
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '') // Remove special characters
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-') // Replace multiple hyphens with single
.replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
}
console.log(generateSlug('Hello World! This is Great'));
// 'hello-world-this-is-great'
Example 2: Password Validator
// Validate password strength
function validatePassword(password) {
const errors = [];
if (password.length < 8) {
errors.push('Password must be at least 8 characters');
}
if (!/[A-Z]/.test(password)) {
errors.push('Password must contain uppercase letter');
}
if (!/[a-z]/.test(password)) {
errors.push('Password must contain lowercase letter');
}
if (!/\d/.test(password)) {
errors.push('Password must contain number');
}
if (!/[!@#$%^&*]/.test(password)) {
errors.push('Password must contain special character');
}
return {
isValid: errors.length === 0,
errors
};
}
console.log(validatePassword('Pass123!'));
// { isValid: true, errors: [] }
Example 3: Text Truncation
// Truncate text with ellipsis
function truncate(text, maxLength = 50, suffix = '...') {
if (text.length <= maxLength) {
return text;
}
return text.slice(0, maxLength - suffix.length) + suffix;
}
console.log(truncate('This is a very long text that needs truncation', 20));
// 'This is a very lo...'
Example 4: Camel Case Converter
// Convert to camelCase
function toCamelCase(str) {
return str
.split(/[\s-_]+/)
.map((word, index) => {
if (index === 0) {
return word.toLowerCase();
}
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
})
.join('');
}
console.log(toCamelCase('hello-world-javascript'));
// 'helloWorldJavascript'
Common Mistakes to Avoid
Mistake 1: Forgetting Strings are Immutable
// โ Wrong - Strings don't change
const str = 'Hello';
str.toUpperCase(); // Returns new string, doesn't modify original
console.log(str); // 'Hello' (unchanged)
// โ
Correct - Assign result
const str = 'Hello';
const upper = str.toUpperCase();
console.log(upper); // 'HELLO'
Mistake 2: Using substr() (Deprecated)
// โ Wrong - substr is deprecated
const str = 'Hello';
console.log(str.substr(0, 3)); // 'Hel'
// โ
Correct - Use slice or substring
console.log(str.slice(0, 3)); // 'Hel'
console.log(str.substring(0, 3)); // 'Hel'
Mistake 3: Not Handling Edge Cases
// โ Wrong - No edge case handling
function getFirstWord(str) {
return str.split(' ')[0];
}
getFirstWord(''); // Returns ''
getFirstWord(' '); // Returns ''
// โ
Correct - Handle edge cases
function getFirstWord(str) {
const trimmed = str.trim();
return trimmed ? trimmed.split(' ')[0] : '';
}
Summary
String methods are essential for text manipulation:
- Use charAt() and bracket notation for character access
- Use indexOf/includes for searching
- Use slice/substring for extraction
- Use split/replace for transformation
- Use match/matchAll for pattern matching
- Strings are immutable - methods return new strings
- Use template literals for concatenation
- Combine methods for complex operations
- Always handle edge cases
- Use regex for advanced pattern matching
Related Resources
Next Steps
Continue your learning journey:
- Array Methods: Complete Reference
- Regular Expressions in JavaScript
- Object Methods: keys, values, entries, assign
- Text Processing & Patterns
Comments