What is the jQuery or JavaScript equivalent of PHP’s strpos() function for finding a string on a page?

Solution: 1

If you want to check whether a string contains a specific character or substring in JavaScript, you can use the indexOf() method. [See documentation here.]

However, if your goal is to search the entire page for text, you can use jQuery’s :contains() selector. [See jQuery docs.]

Example:


var has_string = $('*:contains("search text")');

If the selector returns elements, that means the text exists on the page.

For instance:


var has_string = $('*:contains("Alex JL")').length;
// has_string is 18

var has_string = $('*:contains("horsey rodeo")').length;
// has_string is 0

So you can simply wrap this in an if condition to check whether the text is present.

Solution: 2

You don’t need jQuery for this — plain JavaScript works perfectly well with the .indexOf() method.

If you want something that behaves more like PHP’s strpos(), you can define your own function:


function strpos(haystack, needle, offset) {
  var i = (haystack + '').indexOf(needle, offset || 0);
  return i === -1 ? false : i;
}

This function will return the position of the substring if found, or false if not — just like PHP’s strpos().

(Source: phpjs.org – strpos
)

You can also test it in this [JSFiddle].