Strings are one of the most commonly used data types in JavaScript. They represent text and come with many built-in methods to manipulate and process text efficiently.
This blog explains strings and the most useful string methods with examples.
⭐ 1. What Is a String?
A string is a sequence of characters enclosed in single quotes ('), double quotes ("), or backticks (`) for template literals.
let name1 = "Sagar";
let name2 = 'Sidana';
let greeting = `Hello, ${name1} ${name2}`;
console.log(greeting); // Hello, Sagar Sidana
⭐ 2. String Length
Use the .length property to get the number of characters.
let text = "JavaScript";
console.log(text.length); // 10
⭐ 3. Common String Methods
Changing Case
let name = "sagar";
console.log(name.toUpperCase()); // SAGAR
console.log(name.toLowerCase()); // sagar
Extracting Substrings
let str = "JavaScript";
console.log(str.slice(0, 4)); // Java
console.log(str.substring(4, 10)); // Script
Replacing Text
let str = "I love JS";
let newStr = str.replace("JS", "JavaScript");
console.log(newStr); // I love JavaScript
Trimming Spaces
let str = " Hello World ";
console.log(str.trim()); // "Hello World"
⭐ 4. Splitting and Joining Strings
Split
let fruits = "Apple, Banana, Mango";
let fruitArray = fruits.split(", ");
console.log(fruitArray); // ["Apple","Banana","Mango"]
Join
let newStr = fruitArray.join(" | ");
console.log(newStr); // Apple | Banana | Mango
⭐ 5. Searching in Strings
let str = "I love JavaScript";
console.log(str.indexOf("JavaScript")); // 7
console.log(str.includes("love")); // true
console.log(str.startsWith("I")); // true
console.log(str.endsWith("Script")); // true
⭐ 6. Template Literals (ES6)
Template literals allow multiline strings and variable interpolation.
let name = "Sagar";
let age = 22;
let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);
⭐ Conclusion
Strings are fundamental in JavaScript, and knowing the variety of string methods allows you to manipulate and format text efficiently. Mastering strings is essential for both beginner and advanced JavaScript programming.
📌 Citations
🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/
🔗 External Javascript Documentation:
https://www.w3schools.com/js/