Javascript 使用 Jquery 查找子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2854527/
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
Find substring with Jquery?
提问by CMS
回答by CMS
You don't really need jQuery for such a simple thing, you can simply use the indexOfmethod of String objects, e.g.:
对于这么简单的事情,您实际上并不需要 jQuery,您可以简单地使用indexOfString 对象的方法,例如:
var str = "foobar";
var containsFoo = str.indexOf('foo') >= 0; // true
The indexOfmethod returns the character index where the first occurrence of the specified value is encountered, if not found, it returns -1.
该indexOf方法返回遇到指定值第一次出现的字符索引,如果未找到,则返回-1。
回答by Anurag
Why use 10 characters when 100 will do?
当 100 个字符时为什么要使用 10 个字符?
Here's the requested jQuery plugin:
这是请求的 jQuery 插件:
jQuery.isSubstring = function(haystack, needle) {
return haystack.indexOf(needle) !== -1;
};
Usage:
用法:
$.isSubstring("hello world", "world")); // true;???????????
回答by Jason Jong
If your limited to jQuery which is just JavaScript... you can use the filter
如果您仅限于 jQuery,它只是 JavaScript……您可以使用过滤器
var subgtSel = $("#jquerySelector").filter(function(i) {
// do your filter here
return $(this).attr("data-timestamp") <= subMsg.CreateDateTimeStamp;
});
the subgtSelbecomes your new jQuery now with the relevant filter in the above. In the above, I am looking for all div elements that have an attribute that is less than the subMsg.CreateTimeStamp.
将subgtSel成为新的与上述有关的过滤器现在jQuery的。在上面,我正在寻找属性小于 subMsg.CreateTimeStamp 的所有 div 元素。
If your looking for a particular substring... you can do the following with jQuery right in the selector
如果您正在寻找特定的子字符串...您可以在选择器中使用 jQuery 执行以下操作
var sel = $("#jquerySelector:contains('text')");

