Strings and String Methods
Working with Text
In JavaScript, any text data is called a String. You can create a string by wrapping text in single quotes, double quotes, or backticks.
let myName = "Himanshu Dubey";
let role = 'Software Engineer';
String Properties and Methods
JavaScript provides a ton of built-in features to manipulate strings without you having to write complex logic.
1. Length Property To find out how many characters are in a string (including spaces):
let myName = "Himanshu";
console.log(myName.length); // Outputs: 8
2. toUpperCase() and toLowerCase()
let greeting = "Hello World";
console.log(greeting.toUpperCase()); // "HELLO WORLD"
console.log(greeting.toLowerCase()); // "hello world"
3. slice() Used to extract a portion of a string. You provide the starting index and the ending index (optional). Remember, JavaScript is zero-indexed!
let channel = "Himubey Learn";
console.log(channel.slice(0, 7)); // "Himubey"
4. replace() Replaces a specified value with another value in a string.
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "Himubey.in");
console.log(newText); // "Please visit Himubey.in!"
There are many more methods like concat(), trim(), and split(). As a developer, manipulating text is something you will do daily!
💡 Himanshu's Tip:
Don't try to memorize every single string method. Memorize the top 5 (slice, replace, toUpperCase, split, trim) and use MDN (Mozilla Developer Network) docs for the rest. Even Senior Developers look up string methods every week!
Interview Questions
- What does it mean when we say strings are "immutable" in JavaScript?
- How does the
slice()method handle negative indexes? - What is the difference between
replace()andreplaceAll()?