web analytics

JavaScript Array Iteration

To iterate over an array in JavaScript, you can use a for loop, a while loop, or one of the built-in array iterator methods: forEach(), map(), filter(), reduce(), some(), every(), find(), and findIndex().

For loop

The for loop is the most basic way to iterate over an array. It works by looping over the array elements from beginning to end, executing a code block for each element.

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

This code will print the following output to the console:

1 2 3 4 5

While loop

The while loop is another way to iterate over an array. It works by looping over the array elements while a condition is true.

const numbers = [1, 2, 3, 4, 5];

let i = 0;
while (i < numbers.length) {
console.log(numbers[i]);
i++;
}

This code will produce the same output as the for loop example above.

Built-in array iterator methods

JavaScript provides a number of built-in array iterator methods that can be used to iterate over arrays in different ways.

ForEach() – The forEach() method executes a callback function for each element in the array.

Map() – The map() method creates a new array populated with the results of calling a callback function on each element in the original array.

Filter() – The filter() method creates a new array populated with the elements in the original array that pass a test specified by a callback function.

Reduce() – The reduce() method reduces an array to a single value by applying a callback function to each element in the array.

Some() – The some() method returns true if any element in the array passes a test specified by a callback function.

Every() – The every() method returns true if all elements in the array pass a test specified by a callback function.

Find() – The find() method returns the first element in the array that passes a test specified by a callback function.

FindIndex() – The findIndex() method returns the index of the first element in the array that passes a test specified by a callback function.

Examples

Here are some examples of how to use the built-in array iterator methods:

// forEach()
const numbers = [1, 2, 3, 4, 5];

numbers.forEach((number) => {
console.log(number);
});
// map()
const doubledNumbers = numbers.map((number) => {
return number * 2;
});

console.log(doubledNumbers);
// filter()
const evenNumbers = numbers.filter((number) => {
return number % 2 === 0;
});

console.log(evenNumbers);
// reduce()
const sumOfNumbers = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);

console.log(sumOfNumbers);

// some()
const isAnyNumberDivisibleByThree = numbers.some((number) => {
return number % 3 === 0;
});

console.log(isAnyNumberDivisibleByThree);

// every()
const isEveryNumberDivisibleByTwo = numbers.every((number) => {
return number % 2 === 0;
});

console.log(isEveryNumberDivisibleByTwo);

// find()
const firstEvenNumber = numbers.find((number) => {
return number % 2 === 0;
});

console.log(firstEvenNumber);

// findIndex()
const indexOfTheFirstEvenNumber = numbers.findIndex((number) => {
return number % 2 === 0;
});

console.log(indexOfTheFirstEvenNumber);

Conclusion

JavaScript array iteration is a powerful tool that can be used to perform a variety of tasks on arrays. By understanding the different ways to iterate over arrays, you can write more efficient and concise code.

JavaScript Sorting Arrays

JavaScript arrays are mutable, meaning that their contents can be changed. One way to change the contents of an array is to sort it. The sort() method allows you to sort the elements of an array in ascending or descending order.

Sorting Arrays of Numbers

To sort an array of numbers in ascending order, you can use the following code:

const numbers = [5, 10, 3, 2, 1];
numbers.sort();
console.log(numbers);

This will output the following to the console:

[1, 2, 3, 5, 10]

To sort an array of numbers in descending order, you can use the following code:

const numbers = [5, 10, 3, 2, 1];
numbers.sort((a, b) => b - a);
console.log(numbers);

This will output the following to the console:

[10, 5, 3, 2, 1]

Sorting Arrays of Strings

To sort an array of strings in ascending order, you can use the following code:

const strings = ["apple", "banana", "orange", "cherry"];
strings.sort();
console.log(strings);

This will output the following to the console:

["apple", "banana", "cherry", "orange"]

To sort an array of strings in descending order, you can use the following code:

const strings = ["apple", "banana", "orange", "cherry"];
strings.sort((a, b) => b.localeCompare(a));
console.log(strings);

This will output the following to the console:

["orange", "cherry", "banana", "apple"]

Sorting Arrays of Objects

To sort an array of objects, you can use the sort() method and provide a compare function. The compare function should compare two elements of the array and return a negative number if the first element should come before the second element, a positive number if the second element should come before the first element, and 0 if the elements should remain in the same order.

For example, the following code sorts an array of objects by their name property in ascending order:

const objects = [{ name: "Alice" }, { name: "Bob" }, { name: "Carol" }];
objects.sort((a, b) => a.name.localeCompare(b.name));
console.log(objects);

This will output the following to the console:

[
{ name: "Alice" },
{ name: "Bob" },
{ name: "Carol" }
]

You can also use the sort() method to sort an array of objects by a nested property. For example, the following code sorts an array of objects by their age property in descending order:

const objects = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Carol", age: 20 }
];
objects.sort((a, b) => b.age - a.age);
console.log(objects);

This will output the following to the console:

[
{ name: "Bob", age: 30 },
{ name: "Alice", age: 25 },
{ name: "Carol", age: 20 }
]

Conclusion

The sort() method is a powerful tool for sorting arrays in JavaScript. You can use it to sort arrays of numbers, strings, objects, and any other type of data. By providing a compare function, you can customize the sorting algorithm to meet your specific needs.

JavaScript Array Methods

JavaScript array methods are functions that can be used to perform various operations on arrays, such as adding and removing elements, sorting, filtering, and searching. Array methods are very powerful and can be used to make working with arrays much easier and more efficient.

Here is a detailed tutorial for JavaScript array methods:

Creating an array

To create an array in JavaScript, you can use the array literal syntax, which is a pair of square brackets with a comma-separated list of elements inside. For example:

const fruits = ["apple", "banana", "orange"];

This creates an array with three elements: “apple”, “banana”, and “orange”.

Accessing array elements

To access an element in an array, you can use the square bracket notation. The index of the first element in an array is 0, and the index of the last element is the length of the array minus 1. For example:

const firstFruit = fruits[0]; // “apple”
const lastFruit = fruits[fruits.length - 1]; // “orange”

Adding and removing elements

There are a number of different ways to add and remove elements from an array. Here are a few examples:

To add an element to the end of an array, you can use the push() method. For example:

fruits.push("mango");

To add an element to the beginning of an array, you can use the unshift() method. For example:

fruits.unshift("watermelon");

To remove the last element from an array, you can use the pop() method. For example:

fruits.pop();

To remove the first element from an array, you can use the shift() method. For example:

fruits.shift();

Sorting arrays

To sort an array in ascending or descending order, you can use the sort() method. For example:

fruits.sort(); // sorts the array in ascending order
fruits.sort().reverse(); // sorts the array in descending order

Filtering arrays

To create a new array with only the elements that match a certain condition, you can use the filter() method. For example:

const citrusFruits = fruits.filter(fruit => fruit.includes("citrus"));

This will create a new array called citrusFruits that only contains the fruits from the original array that contain the word “citrus”.

Searching arrays

To find the index of a particular element in an array, you can use the indexOf() method. For example

const indexOfApple = fruits.indexOf("apple"); // 0

If the element is not found in the array, the indexOf() method will return -1.

Other useful array methods

There are a number of other useful array methods, such as:

Map(): Transforms each element in the array using a callback function.

Reduce(): Reduces the array to a single value using a callback function.

Every(): Checks if all elements in the array pass a test.

Some(): Checks if at least one element in the array passes a test.

Concat(): Creates a new array by combining two or more arrays.

Example

Here is an example of how to use some of the JavaScript array methods in action:

const fruits = ["apple", "banana", "orange", "mango"];
// Add a new element to the end of the array.
fruits.push("watermelon");
// Remove the first element from the array.
fruits.shift();
// Sort the array in ascending order.
fruits.sort();
// Filter the array to only include citrus fruits.
const citrusFruits = fruits.filter(fruit => fruit.includes("citrus"));
// Search the array for the index of the element “banana”.
const indexOfBanana = fruits.indexOf("banana");
// Print the results.
console.log(fruits); // [“orange”, “mango”, “watermelon”]
console.log(citrusFruits); // [“orange”]
console.log(indexOfBanana); // 1

Conclusion

JavaScript array methods are a powerful tool that can make working with arrays much easier and more efficient. By learning how to use array methods, you can write more concise and readable code.

JavaScript Arrays

A JavaScript array is a collection of values that can be of any type, including strings, numbers, objects, and other arrays. Arrays are ordered, meaning that the values in the array are stored in a specific order. This order can be accessed using the array’s index, which is a number that starts at 0 and increases by 1 for each item in the array.

Creating JavaScript Arrays

There are two ways to create JavaScript arrays:

Array literal: This is the most common way to create an array. To do this, simply place the values of the array inside square brackets, separated by commas. For example:

const fruits = ["apple", "banana", "orange"];

Array constructor: The Array constructor can also be used to create arrays. To do this, pass the values of the array to the constructor as arguments. For example:

const fruits = new Array("apple", "banana", "orange");

Accessing Array Elements

To access an element in an array, use square brackets and the element’s index. For example, to access the first element in the fruits array, you would use the following code:

const firstFruit = fruits[0];

This will assign the string “apple” to the variable firstFruit.

Modifying Array Elements

To modify an element in an array, simply assign a new value to the element at the desired index. For example, to change the first element in the fruits array to “pear”, you would use the following code:

fruits[0] = "pear";

Adding and Removing Array Elements

To add an element to an array, use the push() method. To remove an element from an array, use the pop() method. Both of these methods return the element that was added or removed.

For example, to add the string “mango” to the fruits array, you would use the following code:

fruits.push("mango");

To remove the last element from the fruits array, you would use the following code:

const lastFruit = fruits.pop();

Iterating Over Arrays

There are a few different ways to iterate over arrays in JavaScript. The most common way is to use a for loop. For example, the following code iterates over the fruits array and prints each element to the console:

for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

Another way to iterate over arrays is to use the forEach() method. The forEach() method takes a callback function as an argument, which is called for each element in the array. For example, the following code iterates over the fruits array and prints each element to the console using the forEach() method:

fruits.forEach(fruit => {
console.log(fruit);
});

JavaScript Array Methods

JavaScript arrays have a number of built-in methods that can be used to perform common tasks, such as sorting, filtering, and searching. For example, the following code sorts the fruits array in alphabetical order:

fruits.sort();

The following code filters the fruits array to only include elements that start with the letter “a”:

const filteredFruits = fruits.filter(fruit => fruit.startsWith("a"));

The following code searches the fruits array for the element “banana” and returns its index:

const bananaIndex = fruits.indexOf("banana");

Conclusion

JavaScript arrays are a powerful tool for storing and manipulating data. By learning how to create, access, and modify arrays, you can write more efficient and maintainable JavaScript code.

Here are some additional tips for using JavaScript arrays:

Use arrays to store related data. For example, you could use an array to store the names of all the users in your application, or the products in your online store.

Use arrays to iterate over data. For example, you could use a for loop to iterate over an array of products and print their prices to the console.

Use array methods to perform common tasks, such as sorting, filtering, and searching. This can save you a lot of time and code.

JavaScript Number Properties

Numbers are one of the most fundamental data types in JavaScript. They can be used to represent a wide variety of values, from simple integers to complex floating-point numbers. JavaScript also provides a number of built-in properties that can be used to manipulate and query numbers.

Standard Number Properties

The following table lists the standard Number properties:

PropertyDescription
EPSILONThe smallest positive number that can be represented accurately by JavaScript.
MAX_SAFE_INTEGERThe largest integer that can be represented accurately by JavaScript without losing precision.
MAX_VALUEThe largest possible numeric value that can be represented by JavaScript.
MIN_SAFE_INTEGERThe smallest integer that can be represented accurately by JavaScript without losing precision.
MIN_VALUEThe smallest possible numeric value that can be represented by JavaScript.
NaNThe special value “Not a Number”.
NEGATIVE_INFINITYThe special value “Negative Infinity”.
POSITIVE_INFINITYThe special value “Positive Infinity”.

These properties can be accessed using the Number object. For example, to get the largest possible numeric value that can be represented by JavaScript, you would use the following code:

const maxValue = Number.MAX_VALUE;

Using Number Properties

The standard Number properties can be used in a variety of ways. For example, you can use them to check whether a number is within a certain range, or to convert a number to a different format.

Here are a few examples:

// Check if a number is within the range of safe integers.
const isSafeInteger = (number) => {
return number >= Number.MIN_SAFE_INTEGER && number <= Number.MAX_SAFE_INTEGER;
};
// Convert a number to exponential notation.
const toExponential = (number) => {
return number.toExponential();
};
// Convert a number to a string with two decimal places.
const toFixed = (number) => {
return number.toFixed(2);
};

Other Number Properties

In addition to the standard Number properties, there are a number of other Number properties that can be used to manipulate and query numbers. These properties are defined on the Number.prototype object.

For example, the Number.prototype.isFinite() method can be used to check whether a number is a finite number. The Number.prototype.isNaN() method can be used to check whether a number is the special value NaN.

Here are a few examples:

// Check if a number is a finite number.
const isFinite = (number) => {
return number.isFinite();
};

// Check if a number is the special value NaN.
const isNaN = (number) => {
return number.isNaN();
};
// Get the absolute value of a number.
const abs = (number) =>; {
return Math.abs(number);
};

Conclusion

JavaScript Number properties provide a variety of ways to manipulate and query numbers. By understanding how to use these properties, you can write more efficient and robust JavaScript code.

JavaScript Number Methods

JavaScript Number methods are functions that can be performed on numbers. They can be used to convert numbers to different formats, check their properties, and perform other operations.

To use a Number method, simply prefix the method name with the Number object. For example, to call the isInteger() method, you would use the following syntax:

Number.isInteger(10); // returns true

Note that Number methods can only be called on the Number object, not on individual number variables. For example, the following code will result in an error:

const x = 10;
x.isInteger();
// TypeError: x.isInteger is not a function

Common JavaScript Number Methods

Here is a list of some of the most common JavaScript Number methods:

Number(): Converts a value to a number. If the value cannot be converted, NaN is returned.

ParseInt(): Parses a string and returns an integer number parsed from the string.

ParseFloat(): Parses a string and returns a floating-point number parsed from the string.

ToExponential(): Returns a string that represents the exponential notation of the given number.

ToFixed(): Returns a string that represents a number formatted using fixed-point notation.

ToPrecision(): Returns a string that represents a number formatted using a specified precision.

ToLocaleString(): Returns a string that represents the number formatted according to the locale specified by the locales parameter.

IsInteger(): Returns true if the number is an integer, false otherwise.

IsFinite(): Returns true if the number is a finite number, false otherwise.

IsNaN(): Returns true if the number is NaNfalse otherwise.

Examples

Here are some examples of how to use JavaScript Number methods:

// Convert a string to a number
const str = "10";
const num = Number(str);
console.log(num);
// 10
// Parse a string as an integer
const str = "10.5";
const int = parseInt(str);
console.log(int);
// 10
// Parse a string as a floating-point number
const str = "10.5";
const float = parseFloat(str);
console.log(float);
// 10.5
// Format a number using exponential notation
const num = 123456789.0123456;
const exp = num.toExponential(2);
console.log(exp);
// 1.23e+8
// Format a number using fixed-point notation
const num = 123456789.0123456;
const fixed = num.toFixed(2);
console.log(fixed);
// 123456789.01
// Format a number using a specified precision
const num = 123456789.0123456;
const precision = num.toPrecision(8);
console.log(precision);
// 1.2345679e+8
// Format a number according to the locale specified by the `locales` parameter
const num = 123456789.0123456;
const locale = "en-US";
const localeString = num.toLocaleString(locale);
console.log(localeString);
// 123,456,789.01

Conclusion

JavaScript Number methods are a powerful tool for working with numbers. By learning how to use these methods, you can perform a variety of operations on numbers, such as converting them to different formats, checking their properties, and formatting them for display.

JavaScript BigInt

Introduction

BigInt is a primitive type in JavaScript that allows you to represent whole numbers larger than 253 – 1. This is because JavaScript numbers are stored in a 64-bit floating-point format, which limits the largest integer that can be represented to 9,007,199,254,740,991.

Creating BigInts

There are two ways to create BigInts:

Using the BigInt literal syntax: You can create a BigInt literal by appending the letter n to the end of an integer literal. For example:

const bigInt1 = 12345678901234567890n;

Using the BigInt() function: You can also create a BigInt using the BigInt() function. The BigInt() function takes an integer literal or string as its argument and returns a BigInt value. For example:

const bigInt2 = BigInt(12345678901234567890);

Using BigInts

Once you have created a BigInt, you can use it like any other JavaScript number. You can perform arithmetic operations on BigInts, compare them, and convert them to other types.

Here are some examples of using BigInts:

// Add two BigInts
const bigIntSum = bigInt1 + bigInt2;
// Subtract two BigInts
const bigIntDifference = bigInt1 - bigInt2;
// Multiply two BigInts
const bigIntProduct = bigInt1 * bigInt2;
// Divide two BigInts
const bigIntQuotient = bigInt1 / bigInt2;
// Compare two BigInts
const isBigInt1GreaterThanBigInt2 = bigInt1 > bigInt2;
// Convert a BigInt to a string
const bigIntAsString = bigInt1.toString();

BigInt Coercion

Many built-in JavaScript operations that expect numbers will automatically coerce BigInts to numbers. This means that you can use BigInts in most places where you would normally use numbers.

However, there are a few things to keep in mind when using BigInt coercion:

Coercing a BigInt to a number can lead to loss of precision, if the BigInt is too large to be represented as a number.

Some built-in operations, such as the Math.floor() and Math.ceil() functions, will truncate the BigInt to a fixed width after coercion.

It is generally recommended to only use BigInt coercion when it is necessary, and to avoid coercing BigInts to numbers if you are unsure whether the number will be too large to be represented accurately.

Use Cases for BigInts

BigInts can be used in a variety of applications, including:

Cryptography: BigInts are often used in cryptography to encrypt and decrypt data.

Financial applications: BigInts are used in financial applications to represent large monetary values.

Scientific computing: BigInts are used in scientific computing to perform calculations on large numbers.

Conclusion

BigInts are a powerful tool that can be used to represent and manipulate very large numbers. If you need to work with numbers that are too large to be represented as JavaScript numbers, then BigInts are the way to go.

Here are some additional tips for using BigInts:

Be aware of the precision limitations of BigInt coercion.

Avoid coercing BigInts to numbers if you are unsure whether the number will be too large to be represented accurately.

Use the BigInt() function to create BigInts from strings, as this is more efficient than parsing the string yourself.

Use the BigInt.asIntN() and BigInt.asUintN() methods to convert BigInts to fixed-width integers.

Be aware that some built-in operations, such as the Math.floor() and Math.ceil() functions, will truncate the BigInt to a fixed width after coercion.

JavaScript Numbers

What are JavaScript Numbers?

JavaScript numbers are primitive data types that can represent both integers and floating-point values. They are stored in 64-bit format using the IEEE-754 standard. This means that JavaScript numbers can have a very large range of values, from approximately -1.8 × 10^308 to 1.8 × 10^308.

Creating JavaScript Numbers

There are two main ways to create JavaScript numbers:

Using number literals: Number literals are simply numeric values written in the code. For example, the following code creates two JavaScript numbers:

const myInteger = 10;
const myFloat = 3.14;

Using the Number() constructor: The Number() constructor can be used to convert any value to a number, if possible. For example, the following code converts the string “10” to a number:

const myNumber = Number("10");

Arithmetic Operations

JavaScript supports all of the standard arithmetic operations on numbers, including addition, subtraction, multiplication, division, and exponentiation. These operations can be performed using the following operators:

Operator | Description
------- | --------
+ | Addition
- | Subtraction
* | Multiplication
/ | Division
** | Exponentiation

For example, the following code performs some basic arithmetic operations on numbers:

const sum = 10 + 5; // sum is now 15
const difference = 10 - 5; // difference is now 5
const product = 10 * 5; // product is now 50
const quotient = 10 / 5; // quotient is now 2
const exponent = 10 ** 2; // exponent is now 100

Number Comparison

JavaScript also supports the following operators for comparing numbers:

Operator | Description
------- | --------
== | Equal to
!= | Not equal to
< | Less than
> | Greater than
<= | Less than or equal to
>= | Greater than or equal to

For example, the following code compares two numbers:

const num1 = 10;
const num2 = 5;
if (num1 == num2) {
console.log("The numbers are equal.");
} else if (num1 > num2) {
console.log("The first number is greater than the second number.");
} else {
console.log("The first number is less than the second number.");
}

Output:

The first number is greater than the second number.

Number Methods

JavaScript provides a number of methods for working with numbers. Some of the most useful methods include:

ToString(): Converts a number to a string.

ToFixed(): Formats a number to a specific number of decimal places.

ToPrecision(): Formats a number to a specific number of significant digits.

ParseInt(): Parses a string into an integer.

ParseFloat(): Parses a string into a floating-point number.

For example, the following code uses the toString(), toFixed(), and parseFloat() methods to work with numbers:

const myNumber = 10.3456;
// Convert the number to a string.
const myString = myNumber.toString();
// Format the number to two decimal places.
const formattedNumber = myNumber.toFixed(2);
// Parse the string into a floating-point number.
const parsedNumber = parseFloat(myString);
console.log(myString); // Output: “10.3456”
console.log(formattedNumber); // Output: “10.35”
console.log(parsedNumber); // Output: 10.3456

Conclusion

JavaScript numbers are a powerful tool that can be used to perform a variety of tasks, such as mathematical calculations, data analysis, and graphics programming. By understanding the basics of JavaScript numbers, you can write more efficient and effective code.

JavaScript Template Literals

JavaScript template literals, also known as template strings, are a new feature introduced in ES6. They allow you to create strings in a more flexible and powerful way than with traditional single or double quotes.

Creating template literals

Template literals are enclosed in backtick (`) characters, instead of single or double quotes. For example:

const name = 'Alice';
const greeting = `Hello, ${name}!`;

The ${name} expression inside the template literal is called a placeholder. When the template literal is evaluated, the placeholder will be replaced with the value of the name variable.

Multi-line strings

Template literals can be used to create multi-line strings without having to escape newline characters. For example:

const poem = `
Roses are red,
Violets are blue,
Sugar is sweet,
And so are you!
`;

This will create a string that contains three lines of text.

String interpolation

Template literals support string interpolation, which allows you to embed variables and expressions inside strings. For example:

const age = 25;
const welcomeMessage = `Welcome to our website, ${age}-year-old ${name}!`;

When this template literal is evaluated, the <span class="math-inline">\{age\}\ and `{name}placeholders will be replaced with the values of theageandname` variables, respectively.

Tagged templates

Tagged templates are a special type of template literal that allows you to pass the template literal to a function. The function can then perform any operations you want on the different parts of the template literal.

For example, the following code uses a tagged template to create a string that is all uppercase:

function toUpperCase(strings, ...expressions) {
const result = [];
for (let i = 0; i < strings.length; i++) {
result.push(strings[i].toUpperCase());
if (i < expressions.length) {
result.push(expressions[i]);
}
}
return result.join('');
}
const name = ‘Alice’;
const greeting = toUpperCase`Hello, ${name}!`;

When this code is executed, the toUpperCase function will be called with the template literal as its first argument. The function will then return a new string that contains all of the parts of the template literal, but with all of the letters converted to uppercase.

Conclusion

JavaScript template literals are a powerful and flexible feature that can be used to create strings in a more efficient and readable way. They are especially useful for creating multi-line strings and embedding variables and expressions inside strings.

Here are some additional examples of how to use template literals:

To create a string that contains a newline character, simply include the newline character inside the template literal. For example:

const message = `This is the first line of the message.
This is the second line of the message.`;

To escape a backtick (`) character inside a template literal, use a backslash () before the backtick. For example:

const message = `This is a template literal with a backtick character (\`).`;

To use a template literal as a template for a regular expression, use the RegExp constructor. For example:

const regex = new RegExp(/^\d{3}-\d{2}-\d{4}$/); // Matches a US phone number

To use a template literal as a template for an HTML element, use the innerHTML property. For example:

const element = document.createElement('div');
element.innerHTML =

This is a heading

;

JavaScript String Search

Overview

JavaScript string search allows you to find the index of a substring within a string. This can be useful for a variety of tasks, such as finding the first occurrence of a character in a string, removing all occurrences of a word from a string, or replacing all occurrences of a string with another string.

Methods

There are two main methods for performing string search in JavaScript:

IndexOf() – This method returns the index of the first occurrence of a substring within a string. If the substring is not found, the method returns -1.

LastIndexOf() – This method returns the index of the last occurrence of a substring within a string. If the substring is not found, the method returns -1.

Examples

The following examples demonstrate how to use the indexOf() and lastIndexOf() methods to perform string search in JavaScript:

// indexOf()
const string = "Hello, world!";
const index = string.indexOf("world");
console.log(index);
// 7
// lastIndexOf()
const index = string.lastIndexOf("world");
console.log(index);
// 7

Advanced Search

In addition to the indexOf() and lastIndexOf() methods, there are a number of other methods that can be used for more advanced string search in JavaScript. These methods include:

Match() – This method returns an array of all occurrences of a substring within a string. If the substring is not found, the method returns null.

Search() – This method returns the index of the first occurrence of a regular expression within a string. If the regular expression is not found, the method returns -1.

Replace() – This method replaces all occurrences of a substring within a string with another string.

Examples

The following examples demonstrate how to use the match(), search(), and replace() methods to perform more advanced string search in JavaScript:

// match()
const string = "Hello, world!";
const matches = string.match("world");
console.log(matches);
// [“world”]
// search()
const string = "Hello, world!";
const index = string.search(/world/);
console.log(index);
// 7
// replace()
const string = "Hello, world!";
const newString = string.replace("world", "universe");
console.log(newString);
// “Hello, universe!”

Conclusion

JavaScript string search is a powerful tool that can be used for a variety of tasks. By understanding the different methods available, you can perform string search efficiently and effectively.