π§΅ String in JavaScript
π What is a String?
A string in JavaScript is a **sequence of characters** used to represent text. Strings are one of the **primitive data types** in JavaScript and are enclosed in quotes: single ('), double ("), or backticks (`).
Code Snippet
const str1 = "Hello";
const str2 = 'World';
const str3 = `Hello, ${str2}!`; // Template literalπ€ String Length
The .length property returns the number of characters in the string.
Code Snippet
const msg = "JavaScript";
console.log(msg.length); // 10π Accessing Characters
Access characters using bracket notation or charAt():
Code Snippet
const word = "code";
console.log(word[0]); // "c"
console.log(word.charAt(1)); // "o"π§ Common String Methods
- toUpperCase() / toLowerCase() β change case
- trim() β removes leading/trailing whitespace
- slice() β extract part of a string
- substring() β similar to slice()
- replace() / replaceAll() β replace text
- includes(), startsWith(), endsWith() β search
Code Snippet
const text = " Hello World! ";
console.log(text.trim()); // "Hello World!"
console.log(text.toUpperCase()); // " HELLO WORLD! "
console.log(text.includes("World")); // true
console.log(text.slice(1, 6)); // "Hello"π¦ String Concatenation
You can join strings using + or template literals:
Code Snippet
const name = "Alice";
console.log("Hello " + name); // Hello Alice
console.log(`Welcome, ${name}!`); // Welcome, Alice!π Iterating Over a String
Code Snippet
const str = "abc";
for (let char of str) {
console.log(char);
}
// a
// b
// cπ Immutability
Strings are **immutable** in JavaScript. Once created, their characters cannot be changed directly.
Code Snippet
let s = "hello";
s[0] = "H";
console.log(s); // still "hello"Note
Use methods to create a modified version instead of changing directly.
π§ͺ Converting Other Types to String
Code Snippet
String(123); // "123"
(456).toString(); // "456"
true + ""; // "true"ποΈ The String() Function
String() is a built-in function that converts any value into its string representation. Unlike calling toString(), it safely works with all values, including null and undefined.
Code Snippet
console.log(String(123)); // "123"
console.log(String(true)); // "true"
console.log(String(null)); // "null"
console.log(String(undefined)); // "undefined"
console.log(String([1, 2, 3])); // "1,2,3"
console.log(String({})); // "[object Object]"Note
π‘ Prefer String(value) when converting unknown values because it never throws an error. In contrast, calling value.toString()on null or undefined results in a TypeError.
String() vs toString()
String(null); // "null"
String(undefined); // "undefined"
null.toString(); // β TypeError
undefined.toString(); // β TypeErrorπ§Ύ Summary
- Strings represent sequences of text characters.
- They are immutable and primitive.
- Template literals support multi-line and interpolation.
- Many built-in methods help manipulate strings.
>>βStrings are the voice of your application β keep them clean and clear.β