JS String Methods 🎯

beginner
11 min

JS String Methods 🎯

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!

What are String Methods? 📝

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.

Creating a String 💡

First, let's create a string. In JavaScript, strings are enclosed in single quotes (') or double quotes (").

javascript
let myString = 'Hello, World!';

Basic String Methods 📝

Length

The length property returns the number of characters in a string.

javascript
let myString = 'Hello, World!'; let stringLength = myString.length; console.log(stringLength); // Output: 13

Concatenation (+)

You can concatenate (join) strings using the + operator.

javascript
let greeting = 'Hello, '; let name = 'World!'; let message = greeting + name; console.log(message); // Output: Hello, World!

Indexing

You can access characters in a string using indexes. Indexes start at 0 and increase by 1 for each character.

javascript
let myString = 'Hello, World!'; console.log(myString[0]); // Output: H

Advanced String Methods 💡

toUpperCase() and toLowerCase()

These methods convert all characters in a string to either uppercase or lowercase.

javascript
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.

javascript
let myString = 'Hello, World!'; let index = myString.indexOf('World'); console.log(index); // Output: 7

substr() and substring()

These methods extract a part of a string based on a start and (optional) end index.

javascript
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: ell

trim()

The trim() method removes leading and trailing whitespace from a string.

javascript
let myString = ' Hello, World! '; let trimmedString = myString.trim(); console.log(trimmedString); // Output: Hello, World!

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `length` property in JavaScript strings?

Quick Quiz
Question 1 of 1

How can you convert a string to uppercase in JavaScript?

Remember to practice these methods to get comfortable with them! Happy coding! 🚀