Overview


In this lab we will experiment with searching for text or a pattern in a string.

Searching for a Pattern in a String



String's search method takes a pattern argument and searches for the first match, returning the matching index (or -1 for no match).

The search method searches the target string
for an regex pattern and returns the first
matching index (or -1 if no match).

		let str, regex, matchIndex;
		str =
`foo
	A	B   C	D
	boo`;
		regex = /A\s+B\s+\C\s+D/g
		matchIndex = str.search(regex);
		console.log(matchIndex);
		//5
		regex = /AB\s+\C\s+D/g
		matchIndex = str.search(regex);
		console.log(matchIndex);
		//-1

More Example Sources


Here are a couple (among many more) online related example sources: