JavaScript is a versatile language that powers the web. With the growth of the internet and web applications, understanding JavaScript is more crucial than ever. Among its numerous capabilities, JavaScript provides a range of string methods to search and manipulate text. In this article, we will explore some of the most common and powerful string methods, complete with examples to try on any online compiler.
String.indexOf()
The indexOf() method returns the index of the first occurrence of the specified value. If the value isn’t found, it returns -1.
Syntax:
str.indexOf(searchValue[, fromIndex])
Example:
const sentence = "Hello, world! Welcome to JavaScript.";
const position = sentence.indexOf('world');
console.log(position); // Outputs: 7
String.lastIndexOf()
lastIndexOf() is similar to indexOf(), but it returns the last occurrence of the specified value.
Syntax:
str.lastIndexOf(searchValue[, fromIndex])
Example:
const sentence = "JavaScript is fun. Do you love JavaScript?";
const position = sentence.lastIndexOf('JavaScript');
console.log(position); // Outputs: 32
String.search()
This method searches for a specified value using a regular expression and returns its position. If not found, it returns -1.
Syntax:
str.search(regexp)
Example:
const data = "I have 100 apples.";
const result = data.search(/\d+/);
console.log(result); // Outputs: 7
String.match()
The match() method retrieves the matches when matching a string against a regular expression.
Syntax:
str.match(regexp)
Example:
const text = "The rain in Spain.";
const matches = text.match(/ain/g);
console.log(matches); // Outputs: ["ain", "ain"]
String.matchAll()
matchAll() returns an iterator of all the results matching a string against a regular expression, including capturing groups.
Syntax:
str.matchAll(regexp)
Example:
const phrase = "Fame is fleeting; obscurity is forever.";
const pattern = /[a-e]/g;
const matches = [...phrase.matchAll(pattern)];
matches.forEach(match => console.log(match[0]));
String.includes()
This method determines whether a string contains a specified string, returning true
or false
.
Syntax:
str.includes(searchString[, position])
Example:
const message = "JavaScript is amazing!";
console.log(message.includes("amazing")); // Outputs: true
String.startsWith()
startsWith() determines whether a string starts with the characters of a specified string.
Syntax:
str.startsWith(searchString[, position])
Example:
const greeting = "Hello world!";
console.log(greeting.startsWith("Hello")); // Outputs: true
String.endsWith()
Similar to startsWith(), endsWith() determines whether a string ends with the characters of a specified string.
Syntax:
str.endsWith(searchString[, length])
Example:
const farewell = "Goodbye, dear friend.";
console.log(farewell.endsWith("friend.")); // Outputs: true
Get more articles on Java Script
Read more on Shell and Linux related articles
Refer more on python here : Python