Progressive Full Stack Application Development with Live Projects

JavaScript String Handling
JavaScript Lesson

JavaScript String Handling

Every programming language support Strings i.e. a representation of a sequence of characters (word or sentence). Javascript strings are primitive and immutable. All string methods produce a new string without altering the original string.

JavaScript offers a variety of methods for string manipulation. Here are some common techniques along with examples:

1. Concatenation

Example:

let str1 = "Hello";
let str2 = "World";
let result = str1 + " " + str2; // "Hello World"

2. Length

Example:

let str = "Hello World";
let length = str.length; // 11

3. Accessing Characters

Example:

let str = "Hello World";
let firstChar = str[0]; // 'H'
let secondChar = str.charAt(1); // 'e'

4. Substring

Example:

let str = "Hello World";
let sub = str.substring(0, 5); // "Hello"

5. Slice

Example:

let str = "Hello World";
let slice = str.slice(6, 11); // "World"

6.Replace

Example:

let str = "Hello World";
let newStr = str.replace("World", "Universe"); // "Hello Universe"

7. Replace All (ES2021)

Example:

let str = "Hello World, World";
let newStr = str.replaceAll("World", "Universe"); // "Hello Universe, Universe"

8. Uppercase and Lowercase

Example:

let str = "Hello World";
let upper = str.toUpperCase(); // "HELLO WORLD"
let lower = str.toLowerCase(); // "hello world"

9. Trim

Example:

let str = "   Hello World   ";
let trimmed = str.trim(); // "Hello World"

10. Split

Example:

let str = "Hello World";
let parts = str.split(" "); // ["Hello", "World"]

11. Join

Example:

let arr = ["Hello", "World"];
let str = arr.join(" "); // "Hello World"

12. Includes

Example:

let str = "Hello World";
let hasHello = str.includes("Hello"); // true
let hasUniverse = str.includes("Universe"); // false

13. Starts With / Ends With

Example:

let str = "Hello World";
let startsWithHello = str.startsWith("Hello"); // true
let endsWithWorld = str.endsWith("World"); // true

14. Repeat

Example:

let str = "Hello ";
let repeated = str.repeat(3); // "Hello Hello Hello "

15. Pad Start / Pad End

Example:

let str = "5";
let paddedStart = str.padStart(2, "0"); // "05"
let paddedEnd = str.padEnd(2, "0"); // "50"

16. Template Literals

Example:

let name = "World";
let greeting = `Hello ${name}`; // "Hello World"

These examples cover a range of basic to intermediate string manipulations in JavaScript. Feel free to ask if you need more advanced techniques or specific use cases!

Leave a Reply