42

Is there an equivalent function in JavaScript or jQuery similar to strpos in PHP?

I want to locate a string inside an element on a page. The string I'm looking for is:

td class="SeparateColumn"

I would like something where I can run it like this to find:

if $("anystring")
  then do it
3
  • 1
    You use the one already existing in plain Javascript? Commented Oct 20, 2010 at 13:15
  • I see, so you'd like to search an entire page for a string? Commented Oct 20, 2010 at 13:19
  • When I try to use in jQuery I get "indexOf is not a function" Any other way to do this with javascript ? ? ? HELP! Commented Dec 10, 2011 at 22:42

2 Answers 2

62

I assume you mean check whether a string contains a character, and the position in the string - you'd like to use the indexOf() method of a string in JS. Here are the relevant docs.


Okay, so you'd like to search the whole page! The :contains() selector will do that. See the jQuery docs for :contains.

To search every element in the page, use

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

If you get jQuery elements back, then the search was a success. For example, on this very page

var has_string=$('*:contains("Alex JL")').length
//has_string is 18
var has_string=$('*:contains("horsey rodeo")').length
//has_string if 0. So, you could an `if` on this and it would work as expected.
Sign up to request clarification or add additional context in comments.

5 Comments

Of course, the act of including 'horsey rodeo' in the example makes the last part technically false, but we won't get into that conundrum.
sounds good; how can I check if element <td class="SeparateColumn"> has a specific string on this page
@Tom if($('td.SeparateColumn:contains("the string")')){/* do something*/} should do it.
thanks but this fails: if(jQuery("tr.SeparateRow:contains('mycode')"))
@Tom fails in which way? An error, or it doesn't find the string? Oh - you have tr.SeparateRow, I think you mean td.SeparateRow.
47

You don't need jquery for this -- plain old Javascript will do just fine, using the .indexof() method.

However if you really want an exact syntax match for PHP's strpos(), something like this would do it:

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

Note: This function taken from here: http://phpjs.org/functions/strpos:545

JSFiddle

2 Comments

IE8 and below do not support indexOf.
@YouBook that's Array.indexOf(), not String.indexOf(), that is not supported by older versions of IE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.