Open In App

How to Search a String for a Pattern in JavaScript ?

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are two ways to search a string for a pattern in JavaScript.

1. Using string search() Method

The JavaScript string search() method is used to serch a specified substing from the given string and regular expression. It returns the index of the first occurrence of the pattern or -1 if the pattern is not found.

Syntax

str.search( pattern )
JavaScript
// Given String
let s = "GeeksforGeeks";

// Defining the patterns using regular expressions.
let p1 = /G/;  // pattern to find G
let p2 = /k/;  // pattern to find k
let p3 = /p/;  // pattern to find p

// Get the position of patten using string.search() 
// and Display the output
console.log("The index of G is:", s.search(p1)); 
console.log("The index of k is:", s.search(p2)); 
console.log("The index of p is:", s.search(p3)); 

Output
The index of G is: 0
The index of k is: 3
The index of p is: -1

2. Using string match() Method

The string match() method is used to get all matching substrings. It returns an arrray of all substrings if the pattern is found or null if no match is found.

Syntax

string.match( expression )
JavaScript
// Given String
let s = "GeeksforGeeks";

// Get the position of patten using string.search() 
// and Display the output
console.log("The Occurence of Ge:", s.match(/rGe/g)); 
console.log("The Occurence of ee:", s.match(/ee/g)); 
console.log("The Occurence of sf:", s.match(/re/g)); 

Output
The Occurence of Ge: [ 'rGe' ]
The Occurence of ee: [ 'ee', 'ee' ]
The Occurence of sf: null


Similar Reads