Find String Within Another String With JavaScript

Finding needle in haystack, or a string within another string, can be done using either regular expressions, or the more simple string functions. Which to use depends mostly on your requirements.

4311 views

Edited: 2018-06-09 09:05

In JavaScript, Searching for a string within another string can be done with the indexOf() function. When this function is used on a variable containing a text string, it will either return 1 on successfully location, or -1 if no match was found.

This is commonly expressed as the needle in haystack problem, describing a problem where you have to find one or more characters inside a series of other characters. Often this will be simple textural content in a variable.

In this example, the str variable represents the haystack, while the parameter of indexOf() represents the needle:

var str = "This string contains a needle";
var n = str.indexOf("needle");

if (n >= 0) {
  alert("Found");
} else {
  alert("Not Found");
}

Using regular expressions

Regular expressions allows us to return the matched string. This can be very useful when manipulating and changing the HTML on pages dynamically. Sometimes DOM may be easier, however.

Note. When you use regular expressions to change the HTML, be extra careful not to create invalid HTML. It can easily happen when replacing code in a page.

The code below will return the content of the href attribute on a link:

var str = '<a href="https://beamtic.com/" class="myclass">';
var found = str.match(/href="([^"]+)"/i);
if (found) {
 // Outputs the matched content
 // console.log("What do you want! You Space Invader!");
 alert(found[1]);
} else {
 // Insults the fumbling web developer
 // console.log("What do you want! You Space Invader!");
 alert("What do you want! You Space Invader!");
}

Note the found[1] array index, if we used "0" instead of "1" it would simply output href as the returned string.

Instead of using alert boxes when texting stuff, you can also use the console.log() to write directly to the console of your browsers developer tools or the console of your code editor.

Tell us what you think:

Nabi

The correct is `if (n >= 0) {` instead of `if (n >= 1) {`
-1 for no match was found. 0 is first position of haystack.