jQuery or JavaScript equivalent of PHP strpos function to find string on a page

前端 未结 2 718
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 09:05

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

相关标签:
2条回答
  • 2021-01-01 09:24

    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

    0 讨论(0)
  • 2021-01-01 09:28

    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.
    
    0 讨论(0)
提交回复
热议问题