jQuery 或 JavaScript 等价于 PHP strpos 函数以在页面上查找字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3978204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery or JavaScript equivalent of PHP strpos function to find string on a page
提问by Tom
Is there an equivalent function in JavaScript or jQuery similar to strpos
in PHP?
JavaScript 或 jQuery 中是否有类似于strpos
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
回答by JAL
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.
我假设您的意思是检查字符串是否包含字符以及字符串中的位置 - 您想indexOf()
在 JS 中使用字符串的方法。以下是相关文档。
Okay, so you'd like to search the whole page! The :contains()
selector will do that. See the jQuery docsfor :contains
.
好的,所以您想搜索整个页面!该: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. For example, on this very page
如果你得到 jQuery 元素,那么搜索就成功了。例如,在这个页面上
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.
回答by Spudley
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/strpos: 545