Mastering JavaScript | 8 STRING METHODS | PART 3
Welcome back to our "Master JavaScript" course! In this video, we'll continue our exploration of essential JavaScript string methods. As we dive further into the world of strings, you'll gain a deeper understanding of how to effectively manipulate and transform text data.
Let's pick up, where we left off and cover more string methods.
indexOf() and lastIndexOf() The indexOf() method helps you find the first occurrence of a specified substring within a string. while lastIndexOf() does the same but starts searching from the end of the string:
1
2
3
const text = "Hello, World!";
const firstIndex = text.indexOf("o");
console.log(firstIndex);
The includes() method checks whether a substring is present within a string, returning a Boolean value:
1
2
3
const text = "Hello, World!";
const includesHello = text.includes("Hello");
console.log(includesHello); // Output: true
startsWith() and endsWith()
To check if a string starts or ends with a specific substring, use the startsWith()
and endsWith() methods:
1
2
3
4
5
const text = "Hello, World!";
const startsWithHello = text.startsWith("Hello");
console.log(startsWithHello); // Output: true
const endsWithWorld = text.endsWith("World!");
console.log(endsWithWorld); // Output: true
match()
The match() method uses a regular expression to search for matches in a string, returning an array of matches:
1
2
3
4
const text = "Hello, John and Jane!";
const regex = /[A-Z][a-z]+/g;
const matches = text.match(regex);
console.log(matches); // Output: ["Hello", "John", "Jane"]
matchAll()
The matchAll() method is used to find all matches of a regular expression in a string. Unlike match(), which returns an array of matches, matchAll() returns an iterator that allows you to iterate through all matches and their capture groups.
1
2
3
4
5
6
7
8
9
10
11
const text = "Hello, John and Jane!";
const regex = /[A-Z][a-z]+/g;
const matchesIterator = text.matchAll(regex);
for (const match of matchesIterator) {
console.log(`Full match: ${match[0]}`);
}
/* output
Full match: Hello
Full match: John
Full match: Jane
*/
repeat()
the final method in this video is the repeat() method is used to create a new string by repeating the original string a specified number of times.
1
2
3
const text = "Hello!";
const repeatedText = text.repeat(3);
console.log(repeatedText); // Output: "Hello!Hello!Hello!"
at the end I’d like to thank you and to say that you've now expanded your knowledge of JavaScript string methods! If you found this video helpful, remember to give it a thumbs up and stay tuned for more content and subscribe. Happy coding, and see you in the next one!