Welcome back to CodeYourCraft! Today, we're diving into the world of JavaScript (JS) String Methods. We'll explore various methods to manipulate, compare, and analyze strings in your code. Let's get started!
In JavaScript, string methods are functions that operate on strings. They allow us to perform specific actions on strings, such as changing case, finding substrings, and trimming spaces.
First, let's create a string. In JavaScript, strings are enclosed in single quotes (') or double quotes (").
let myString = 'Hello, World!';The length property returns the number of characters in a string.
let myString = 'Hello, World!';
let stringLength = myString.length;
console.log(stringLength); // Output: 13+)You can concatenate (join) strings using the + operator.
let greeting = 'Hello, ';
let name = 'World!';
let message = greeting + name;
console.log(message); // Output: Hello, World!You can access characters in a string using indexes. Indexes start at 0 and increase by 1 for each character.
let myString = 'Hello, World!';
console.log(myString[0]); // Output: HtoUpperCase() and toLowerCase()These methods convert all characters in a string to either uppercase or lowercase.
let myString = 'Hello, World!';
let uppercaseString = myString.toUpperCase();
console.log(uppercaseString); // Output: HELLO, WORLD!
let lowercaseString = myString.toLowerCase();
console.log(lowercaseString); // Output: hello, world!indexOf() and lastIndexOf()These methods search for a specific substring within a string and return its index.
let myString = 'Hello, World!';
let index = myString.indexOf('World');
console.log(index); // Output: 7substr() and substring()These methods extract a part of a string based on a start and (optional) end index.
let myString = 'Hello, World!';
let subString = myString.substr(7, 5);
console.log(subString); // Output: World
let start = 1;
let end = 5;
let anotherSubString = myString.substring(start, end);
console.log(anotherSubString); // Output: elltrim()The trim() method removes leading and trailing whitespace from a string.
let myString = ' Hello, World! ';
let trimmedString = myString.trim();
console.log(trimmedString); // Output: Hello, World!What is the purpose of the `length` property in JavaScript strings?
How can you convert a string to uppercase in JavaScript?
Remember to practice these methods to get comfortable with them! Happy coding! 🚀