简体   繁体   English

jQuery或JavaScript相当于PHP strpos函数在页面上查找字符串

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

Is there an equivalent function in JavaScript or jQuery similar to strpos in PHP? JavaScript或jQuery中的等效函数是否类似于PHP中的strpos

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

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. 我假设你的意思是检查一个字符串是否包含一个字符,以及字符串中的位置 - 你想在JS中使用字符串的indexOf()方法。 Here are the relevant docs . 以下是相关文档


Okay, so you'd like to search the whole page! 好的,所以你想搜索整个页面! The :contains() selector will do that. :contains()选择器会这样做。 See the jQuery docs for :contains . 请参阅jQuery文档 :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. 如果你回来了jQuery元素,那么搜索就是成功的。 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.

You don't need jquery for this -- plain old Javascript will do just fine, using the .indexof() method. 你不需要jquery - 使用.indexof()方法,普通的旧Javascript就可以了。

However if you really want an exact syntax match for PHP's strpos(), something like this would do it: 但是,如果你真的想要PHP的strpos()的精确语法匹配,这样的事情会这样做:

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 注意:此函数取自此处: http//phpjs.org/functions/strpos545

JSFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM