🧡 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.”

πŸ”— References