JavaScript String Search

In javascript, you can search for a substring within a string using the `search()` method or the `indexof()` method. Here's how you can use these methods for string search:


1. `search(searchvalue)`:

the `search()` method searches for a specified substring within a string. It returns the index of the first occurrence of the substring, or -1 if the substring is not found. It supports regular expressions for more advanced search patterns.

javascript
const message = 'hello, world!';
console.log(message.search('world')); // output: 7
console.log(message.search('foo')); // output: -1 (not found)

note: the `search()` method performs a case-insensitive search by default. If you need a case-sensitive search or more advanced search patterns, you can use regular expressions.


2. `indexof(searchvalue, startindex)`:

the `indexof()` method searches for a specified substring within a string, starting from the specified `startindex`. It returns the index of the first occurrence of the substring, or -1 if the substring is not found. It performs a case-sensitive search.

javascript
const message = 'hello, world!';
console.log(message.indexof('world')); // output: 7
console.log(message.indexof('o', 5)); // output: 8 (searching from index 5)
console.log(message.indexof('foo')); // output: -1 (not found)

if you want to find the last occurrence of a substring within a string, you can use `lastindexof()`:

javascript
const message = 'hello, world!';
console.log(message.lastindexof('o')); // output: 8

note: the `indexof()` and `lastindexof()` methods can also be used with regular expressions for advanced search patterns.


It's worth noting that both `search()` and `indexof()` return the position of the first occurrence of the substring. If you need to check if a string contains a substring without getting its position, you can use the `includes()` method:

javascript
Const message = 'hello, world!';
Console.log(message.includes('world')); // output: true
Console.log(message.includes('foo')); // output: false

These methods provide different options for searching within strings in javascript. Choose the appropriate method based on your specific requirements, such as case sensitivity or the need for regular expressions.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext