JavaScript Strings
Strings are one of the basic data types in JavaScript, used to represent text data. In web development, string processing is a very common operation, including user input handling, data formatting, template generation, etc. Mastering string operations is crucial for writing efficient JavaScript code. In this chapter, we will learn in depth about various string operations and processing methods in JavaScript.
What is a String
A string is a sequence of zero or more characters, enclosed in single quotes ('), double quotes ("), or backticks (`). Strings are immutable; once created, they cannot be modified.
// String literals
const singleQuote = 'Single quote string';
const doubleQuote = "Double quote string";
const backtick = `Backtick string`;
// Empty string
const emptyString = "";
const anotherEmpty = '';
// Strings containing quotes
const withQuotes = 'He said: "Hello!"';
const withApostrophe = "This is John's book";Ways to Create Strings
1. String Literals
const str1 = "Hello World";
const str2 = 'JavaScript';
const str3 = `Template string`;2. String Constructor
const str1 = new String("Hello");
const str2 = String("World");
console.log(typeof str1); // "object"
console.log(typeof str2); // "string"3. String Concatenation
const firstName = "John";
const lastName = "Doe";
const fullName = firstName + " " + lastName; // "John Doe"
const greeting = "Hello, " + fullName + "!"; // "Hello, John Doe!"
// Using += operator
let message = "Hello";
message += " World"; // "Hello World"String Properties and Methods
Basic Properties
const str = "JavaScript";
// length property - get string length
console.log(str.length); // 10
// Access individual characters
console.log(str[0]); // "J"
console.log(str.charAt(0)); // "J"
console.log(str.charCodeAt(0)); // 74 (Unicode value)Search Methods
const text = "JavaScript is a powerful programming language, JavaScript is popular";
// indexOf() - find first occurrence of substring
console.log(text.indexOf("JavaScript")); // 0
console.log(text.indexOf("JavaScript", 5)); // 47 (search from position 5)
// lastIndexOf() - find last occurrence of substring
console.log(text.lastIndexOf("JavaScript")); // 47
// includes() - check if substring exists
console.log(text.includes("programming")); // true
console.log(text.includes("Python")); // false
// startsWith() - check if starts with specified string
console.log(text.startsWith("JavaScript")); // true
console.log(text.startsWith("programming")); // false
// endsWith() - check if ends with specified string
console.log(text.endsWith("popular")); // true
console.log(text.endsWith("JavaScript")); // false
// search() - search using regular expression
console.log(text.search(/javascript/i)); // 0 (case insensitive)Extraction Methods
const str = "JavaScript Programming";
// slice() - extract part of string
console.log(str.slice(0, 10)); // "JavaScript"
console.log(str.slice(11)); // "Programming"
console.log(str.slice(-11)); // "Programming" (from last 11 chars)
console.log(str.slice(-11, -1)); // "Programmin"
// substring() - extract part of string
console.log(str.substring(0, 10)); // "JavaScript"
console.log(str.substring(11)); // "Programming"
// substr() - deprecated but still works
console.log(str.substr(0, 10)); // "JavaScript"
console.log(str.substr(11, 4)); // "Prog"Transformation Methods
const str = "JavaScript Programming";
// toUpperCase() - convert to uppercase
console.log(str.toUpperCase()); // "JAVASCRIPT PROGRAMMING"
// toLowerCase() - convert to lowercase
console.log(str.toLowerCase()); // "javascript programming"
// trim() - remove whitespace from both ends
const spacedStr = " Hello World ";
console.log(spacedStr.trim()); // "Hello World"
console.log(spacedStr.trimStart()); // "Hello World "
console.log(spacedStr.trimEnd()); // " Hello World"
// padStart() and padEnd() - pad string
const number = "42";
console.log(number.padStart(5, "0")); // "00042"
console.log(number.padEnd(5, "0")); // "42000"
// repeat() - repeat string
console.log("Hello".repeat(3)); // "HelloHelloHello"Split and Join Methods
const str = "apple,banana,orange";
// split() - split string into array
console.log(str.split(",")); // ["apple", "banana", "orange"]
console.log(str.split(",", 2)); // ["apple", "banana"]
console.log("Hello World".split(" ")); // ["Hello", "World"]
console.log("Hello".split("")); // ["H", "e", "l", "l", "o"]
// join() - join array to string (array method)
const fruits = ["apple", "banana", "orange"];
console.log(fruits.join(", ")); // "apple, banana, orange"
console.log(fruits.join(" | ")); // "apple | banana | orange"Replace Methods
const text = "JavaScript is powerful, JavaScript is popular";
// replace() - replace first match
console.log(text.replace("JavaScript", "Python"));
// "Python is powerful, JavaScript is popular"
// replaceAll() - replace all matches (ES2021)
console.log(text.replaceAll("JavaScript", "Python"));
// "Python is powerful, Python is popular"
// Using regex for replacement
console.log(text.replace(/javascript/gi, "Python"));
// "Python is powerful, Python is popular"
// Using function as replacement value
console.log(text.replace("JavaScript", (match) => match.toUpperCase()));
// "JAVASCRIPT is powerful, JavaScript is popular"Template Literals - ES6
Template strings use backticks (`) and support multi-line strings and expression interpolation.
// Basic usage
const name = "John";
const age = 25;
const greeting = `Hello, I'm ${name}, ${age} years old`;
console.log(greeting); // "Hello, I'm John, 25 years old"
// Multi-line strings
const multiline = `
This is line one
This is line two
This is line three
`;
console.log(multiline);
// Expression interpolation
const a = 5;
const b = 3;
const result = `${a} + ${b} = ${a + b}`;
console.log(result); // "5 + 3 = 8"
// Nested template strings
const price = 100;
const tax = 0.1;
const total = `Total: $${price * (1 + tax)} (including ${tax * 100}% tax)`;
console.log(total); // "Total: $110 (including 10% tax)"
// Tagged Templates
function highlight(strings, ...values) {
let result = "";
strings.forEach((string, i) => {
result += string;
if (values[i]) {
result += `<mark>${values[i]}</mark>`;
}
});
return result;
}
const person = "John";
const skill = "JavaScript";
const description = highlight`I am ${person}, I excel at ${skill} programming`;
console.log(description); // "I am <mark>John</mark>, I excel at <mark>JavaScript</mark> programming"Unicode Handling
// Unicode characters
const unicodeStr = "Hello World 🌍";
// Correct handling of Unicode character length
console.log(unicodeStr.length); // 13
// Use Array.from() to get correct character count
console.log(Array.from(unicodeStr).length); // 12
// codePointAt() - get Unicode code point
console.log("🌍".codePointAt(0)); // 127757
// fromCodePoint() - create character from code point
console.log(String.fromCodePoint(127757)); // "🌍"
// normalize() - Unicode normalization
const str1 = "café"; // Contains combining characters
const str2 = "café"; // Contains precomposed characters
console.log(str1 === str2); // false
console.log(str1.normalize() === str2.normalize()); // trueString Comparison
const str1 = "apple";
const str2 = "Apple";
const str3 = "banana";
// Direct comparison
console.log(str1 === str2); // false (case sensitive)
console.log(str1 < str3); // true (alphabetical order)
// Case-insensitive comparison
console.log(str1.toLowerCase() === str2.toLowerCase()); // true
// localeCompare() - locale-aware comparison
console.log(str1.localeCompare(str2)); // 1 (str1 > str2)
console.log(str1.localeCompare(str2, undefined, { sensitivity: 'base' })); // 0 (ignore case)
// Numeric string comparison
const numStr1 = "10";
const numStr2 = "2";
console.log(numStr1 < numStr2); // true (string comparison)
console.log(Number(numStr1) < Number(numStr2)); // false (number comparison)Performance Optimization
1. String Concatenation Optimization
// For few string concatenations, use + operator
const result1 = "Hello" + " " + "World";
// For many concatenations, use array join
function concatenateStrings(strings) {
return strings.join("");
}
// For string concatenation in loops, use array
function buildString(items) {
const parts = [];
for (let item of items) {
parts.push(`<li>${item}</li>`);
}
return `<ul>${parts.join("")}</ul>`;
}2. String Caching
// Avoid repeatedly creating the same strings
const templates = {
header: "<header>Website Header</header>",
footer: "<footer>Website Footer</footer>"
};
function renderPage(content) {
return templates.header + content + templates.footer;
}Best Practices
1. Input Validation
function validateEmail(email) {
if (typeof email !== "string") {
return false;
}
// Trim whitespace
email = email.trim();
// Basic format check
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function validateUsername(username) {
if (typeof username !== "string") {
return false;
}
// Trim whitespace
username = username.trim();
// Length check
if (username.length < 3 || username.length > 20) {
return false;
}
// Character check
const usernameRegex = /^[a-zA-Z0-9_]+$/;
return usernameRegex.test(username);
}2. String Formatting
// Currency formatting
function formatCurrency(amount) {
return `$${amount.toFixed(2)}`;
}
function formatPercentage(value) {
return `${(value * 100).toFixed(1)}%`;
}
// Date formatting
function formatDate(date) {
if (!(date instanceof Date)) {
date = new Date(date);
}
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
// Phone number formatting
function formatPhoneNumber(phone) {
// Remove all non-digit characters
const digits = phone.replace(/\D/g, "");
// Format as XXX-XXX-XXXX
if (digits.length === 10) {
return `${digits.slice(0, 3)}-${digits.slice(3, 6)}-${digits.slice(6)}`;
}
return phone;
}3. Security Handling
// HTML escaping
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, (m) => map[m]);
}
// URL encoding
function buildQueryString(params) {
const pairs = [];
for (let key in params) {
if (params.hasOwnProperty(key)) {
pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
}
}
return pairs.join("&");
}Practical Examples
1. Simple Template Engine
class SimpleTemplate {
constructor(template) {
this.template = template;
}
render(data) {
let result = this.template;
// Replace {{variable}} pattern
for (let key in data) {
if (data.hasOwnProperty(key)) {
const pattern = new RegExp(`{{\\s*${key}\\s*}}`, 'g');
result = result.replace(pattern, data[key]);
}
}
return result;
}
}
// Usage example
const template = new SimpleTemplate(`
<h1>{{title}}</h1>
<p>Author: {{author}}</p>
<p>Published: {{date}}</p>
<div>{{content}}</div>
`);
const data = {
title: "JavaScript String Handling",
author: "John",
date: "2024-01-01",
content: "This is the article content..."
};
const html = template.render(data);
console.log(html);2. String Utility Library
const StringUtils = {
// Convert to camelCase
toCamelCase(str) {
return str.replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
},
// Convert to PascalCase
toPascalCase(str) {
return str.replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '')
.replace(/^./, (match) => match.toUpperCase());
},
// Convert to snake_case
toSnakeCase(str) {
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
.replace(/^-+/, '');
},
// Generate random string
randomString(length = 10) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
},
// Truncate string
truncate(str, maxLength, suffix = '...') {
if (str.length <= maxLength) {
return str;
}
return str.substring(0, maxLength - suffix.length) + suffix;
},
// Capitalize first letter
capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
},
// Word count
wordCount(str) {
return str.trim().split(/\s+/).filter(word => word.length > 0).length;
}
};
// Usage examples
console.log(StringUtils.toCamelCase("hello-world")); // "helloWorld"
console.log(StringUtils.toPascalCase("hello-world")); // "HelloWorld"
console.log(StringUtils.toSnakeCase("helloWorld")); // "hello_world"
console.log(StringUtils.randomString(8)); // Random 8-char string
console.log(StringUtils.truncate("This is a very long string", 15)); // "This is a ve..."
console.log(StringUtils.capitalize("hello")); // "Hello"
console.log(StringUtils.wordCount("Hello world JavaScript")); // 3Summary
Key points about JavaScript strings:
- Creation Methods: String literal, String constructor
- Basic Properties: length property
- Search Methods: indexOf, lastIndexOf, includes, startsWith, endsWith
- Extraction Methods: slice, substring, substr
- Transformation Methods: toUpperCase, toLowerCase, trim, padStart, padEnd
- Split and Join: split, join
- Replace Methods: replace, replaceAll
- Template Literals: Support multi-line and expression interpolation
- Unicode Handling: Correct handling of multi-byte characters
- Performance Optimization: Choose appropriate concatenation methods
- Best Practices: Input validation, formatting, security handling
Mastering string handling is a fundamental skill for JavaScript development. In the next chapter, we will learn about JavaScript operators.