π·οΈ Strings
In JavaScript, a String is a text type represented using UTF-16 encoding. Strings can be created using:
- Double quotes ("")
- Single quotes ('')
- Backticks (``) β (Template Literal)
1. Ways to Create Strings
Example: Strings created in different ways
const str1 = "Hello"; // Double quotes
const str2 = 'World'; // Single quotes
const str3 = `Welcome, ${str1} ${str2}!`; // Backticks (Template Literal)
Template Literal allows embedding variables using ${}:
const name = "John";
const message = `Hello, ${name}!`; // Hello, John!
2. Key Properties of Strings
Indexing
- Strings can be treated as array-like structures.
- Indexing starts at 0.
const str = 'JavaScript';
console.log(str[0]); // 'J'
console.log(str[4]); // 'S'
console.log(str[str.length - 1]); // 't'
Immutability
- Strings are immutableβthey cannot be modified directly.
- To "change" a string, you must create a new one.
let str = 'Hello';
str[0] = 'h'; // Won't work
str = 'hello'; // Reassignment works
3. Essential Methods
JavaScript provides several built-in string methods:
length β Returns string length
const str = 'JavaScript';
console.log(str.length); // 10
charAt(index) β Returns character at the specified index
const str = 'JavaScript';
console.log(str.charAt(0)); // 'J'
slice(start, end) β Extracts a substring
- start β Starting index
- end β (Optional) End index (exclusive)
const str = 'JavaScript';
console.log(str.slice(0, 4)); // 'Java'
console.log(str.slice(4)); // 'Script'
console.log(str.slice(-6)); // 'Script'
substring(start, end) β Similar to slice but ignores negative values
const str = 'JavaScript';
console.log(str.substring(0, 4)); // 'Java'
console.log(str.substring(4)); // 'Script'
substr(start, length) β Extracts a substring with a specified length
const str = 'JavaScript';
console.log(str.substr(4, 3)); // 'Scr'
toUpperCase() & toLowerCase() β Changes text case
const str = 'JavaScript';
console.log(str.toUpperCase()); // 'JAVASCRIPT'
console.log(str.toLowerCase()); // 'javascript'
trim() β Removes whitespace from both ends
const str = ' Hello World! ';
console.log(str.trim()); // 'Hello World!'
replace() β Replaces a character or substring
const str = 'JavaScript is great';
console.log(str.replace('great', 'awesome')); // 'JavaScript is awesome'
replace() changes only the first match.
Use a regular expression (RegEx) to replace all occurrences:
const str = 'JavaScript is great, JavaScript is fun';
console.log(str.replace(/JavaScript/g, 'JS')); // 'JS is great, JS is fun'
split() β Splits a string into an array using a delimiter
const str = 'JavaScript is fun';
console.log(str.split(' ')); // ['JavaScript', 'is', 'fun']
includes() β Returns true if the substring exists
const str = 'JavaScript is fun';
console.log(str.includes('Script')); // true
console.log(str.includes('script')); // false (case-sensitive)
startsWith() & endsWith()
const str = 'JavaScript';
console.log(str.startsWith('Java')); // true
console.log(str.endsWith('Script')); // true
String Concatenation
Using the + operator
const firstName = 'John';
const lastName = 'Doe';
const fullName = firstName + ' ' + lastName;
console.log(fullName); // 'John Doe'
Using concat()
const firstName = 'John';
const lastName = 'Doe';
const fullName = firstName.concat(' ', lastName);
console.log(fullName); // 'John Doe'
Using Template Literal
const firstName = 'John';
const lastName = 'Doe';
const fullName = `${firstName} ${lastName}`;
console.log(fullName); // 'John Doe'
String vs String Object
Strings can also be created as objects using new String(), but this is not recommended.
const str1 = 'Hello'; // String type
const str2 = new String('Hello'); // String object
console.log(typeof str1); // 'string'
console.log(typeof str2); // 'object'
console.log(str1 === str2); // false
Best practice: Use primitive strings instead of String objects.
Best Practices
- Prefer Template Literals (\``) for clarity and readability.
- Avoid String objects.
- Use includes() and startsWith() for checks.
- Use replaceAll() or RegEx for global replacements.