Working with Strings
const single = 'Hello';const double = "World";const template = `Hello, ${double}!`; // Template literal with interpolationconsole.log(template); // Output: Hello, World!javascript
A string in JavaScript can be created in several ways:
-
Literal Notation:
const str1 = "JavaScript";const str2 = 'is fun';javascript -
String Constructor (less common):
const str3 = new String("Hello"); // Creates a String object (not a primitive)console.log(typeof str3); // Output: objectjavascript- Note: Prefer literals over the constructor for simplicity and performance.
-
Template Literals (ES6+):
const name = "Alice";const greeting = `Hi, ${name}!`; // Supports expressionsconsole.log(greeting); // Output: Hi, Alice!javascript
length: Returns the number of characters in the string.const str = "Hello";console.log(str.length); // Output: 5javascript
const name = "Bob";const message = ` Hello, ${name}! How are you today?`;console.log(message);// Output:// Hello, Bob!// How are you today?javascript
Using Object Properties in Template Literals
Section titled “Using Object Properties in Template Literals”You can access object properties directly within ${} for concise and readable string construction:
const user = { firstName: "Michel", age: 25, address: { city: "Montreal", country: "Canada" }};const greeting = `Welcome, ${user.firstName}! You are ${user.age} years old and live in ${user.address.city}, ${user.address.country}.`;console.log(greeting);// Output: Welcome, Michel! You are 25 years old and live in Montreal, Canada.javascript
You can also include expressions involving object properties:
const product = { name: "Laptop", price: 999.99, discount: 0.1 // 10% discount};const offer = `${product.name} on sale: $${(product.price * (1 - product.discount)).toFixed(2)} after a ${product.discount * 100}% discount!`;console.log(offer);// Output: Laptop on sale: $899.99 after a 10% discount!javascript
Use \ to escape special characters:
\"or\': Include quotes in a string.\n: Newline.\t: Tab.\\: Backslash.
const str = "She said, \"Hi!\"\nNew line.";console.log(str);// Output:// She said, "Hi!"// New line.javascript
charAt(index): Returns the character at the specified index (0-based).const str = "Hello";console.log(str.charAt(1)); // Output: ejavascript[index]: Array-like access (shorter syntax).console.log(str[1]); // Output: ejavascriptcharCodeAt(index): Returns the UTF-16 code of the character at the index.console.log(str.charCodeAt(0)); // Output: 72 (ASCII/UTF-16 code for 'H')javascript
indexOf(substring, [start]): Returns the first index of the substring, or -1 if not found.const str = "Hello World";console.log(str.indexOf("World")); // Output: 6console.log(str.indexOf("z")); // Output: -1javascriptlastIndexOf(substring, [start]): Returns the last index of the substring.console.log(str.lastIndexOf("l")); // Output: 9javascriptincludes(substring, [start]): Returnstrueif the substring exists.console.log(str.includes("Hello")); // Output: truejavascriptstartsWith(substring, [start]): Checks if the string starts with the substring.console.log(str.startsWith("He")); // Output: truejavascriptendsWith(substring, [length]): Checks if the string ends with the substring.console.log(str.endsWith("ld")); // Output: truejavascript
toLowerCase(): Converts the string to lowercase.const str = "HELLO";console.log(str.toLowerCase()); // Output: hellojavascripttoUpperCase(): Converts the string to uppercase.console.log(str.toUpperCase()); // Output: HELLOjavascripttrim(): Removes whitespace from both ends.const str = " Hello ";console.log(str.trim()); // Output: HellojavascripttrimStart()/trimEnd(): Removes whitespace from the start or end.console.log(str.trimStart()); // Output: "Hello "javascriptreplace(search, replacement): Replaces the first match with a new value.const str = "Hello World";console.log(str.replace("World", "JavaScript")); // Output: Hello JavaScriptjavascriptreplaceAll(search, replacement)(ES2021+): Replaces all matches.const str = "Hello Hello";console.log(str.replaceAll("Hello", "Hi")); // Output: Hi Hijavascriptslice(start, [end]): Extracts a portion of the string.const str = "Hello World";console.log(str.slice(0, 5)); // Output: Hellojavascriptsubstring(start, [end]): Similar toslice, but doesn’t accept negative indices.console.log(str.substring(6)); // Output: Worldjavascriptsplit(separator, [limit]): Splits the string into an array based on a separator.const str = "apple,banana,orange";console.log(str.split(",")); // Output: ["apple", "banana", "orange"]javascript
concat(...strings): Combines strings.const str1 = "Hello";const str2 = "World";console.log(str1.concat(" ", str2)); // Output: Hello Worldjavascript- Using
+or+=(more common):console.log(str1 + " " + str2); // Output: Hello Worldjavascript
padStart(targetLength, padString): Pads the start of the string.const str = "5";console.log(str.padStart(3, "0")); // Output: 005javascriptpadEnd(targetLength, padString): Pads the end of the string.console.log(str.padEnd(3, "0")); // Output: 500javascript
repeat(count): Repeats the string a specified number of times.const str = "Hi ";console.log(str.repeat(3)); // Output: Hi Hi Hijavascript
Strings in JavaScript are immutable—methods don’t modify the original string but return a new one:
const str = "Hello";const newStr = str.toUpperCase();console.log(str); // Output: Hello (unchanged)console.log(newStr); // Output: HELLOjavascript
- Use
===for exact comparison (case-sensitive):console.log("hello" === "Hello"); // Output: falsejavascript - Use
localeCompare()for locale-aware comparison:console.log("apple".localeCompare("banana")); // Output: -1 (apple comes before banana)javascript
- Use Template Literals: Prefer backticks for readability and interpolation.
- Avoid Excessive Concatenation: Use arrays and
join()for performance with large strings:const parts = ["Hello", "World"];console.log(parts.join(" ")); // Output: Hello Worldjavascript - Handle Edge Cases: Check for empty strings or
undefined:const str = "";console.log(str.length || "Empty"); // Output: Emptyjavascript - Case Sensitivity: Normalize case with
toLowerCase()ortoUpperCase()when comparing. - Use Modern Methods: Prefer
includes()overindexOf() !== -1for readability.
- Parsing User Input: Split and trim strings from forms.
- Formatting Output: Use template literals for dynamic messages.
- Data Serialization: Convert objects to JSON strings with
JSON.stringify().
- Type Errors: Ensure the value is a string before calling methods (
typeof str === "string"). - Out-of-Bounds: Accessing an invalid index returns
undefined, not an error.console.log("Hello"[10]); // Output: undefinedjavascript - Encoding: Use
encodeURIComponent()for URLs or special characters.
Using Object Properties in Template Literals
Section titled “Using Object Properties in Template Literals”A practical example demonstrating how to use object properties in template literals to generate a formatted message:
// Define an object with nested propertiesconst employee = { id: 123, name: "John Doe", role: "Developer", department: { name: "Engineering", location: "Building A" }, salary: 75000};
// Create a template literal using object propertiesconst employeeSummary = ` Employee ID: ${employee.id} Name: ${employee.name} Role: ${employee.role} Department: ${employee.department.name} Location: ${employee.department.location} Annual Salary: $${employee.salary.toLocaleString("en-US")}`;
// Output the resultconsole.log(employeeSummary);// Output:// Employee ID: 123// Name: John Doe// Role: Developer// Department: Engineering// Location: Building A// Annual Salary: $75,000javascript