Find substring with Jquery?
How would our group find out if a particular string contains a certain substring? Only 开发者_StackOverflow中文版with the help of jquery, please.
You don't really need jQuery for such a simple thing, you can simply use the indexOf
method of String objects, e.g.:
var str = "foobar";
var containsFoo = str.indexOf('foo') >= 0; // true
The indexOf
method returns the character index where the first occurrence of the specified value is encountered, if not found, it returns -1
.
Why use 10 characters when 100 will do?
Here's the requested jQuery plugin:
jQuery.isSubstring = function(haystack, needle) {
return haystack.indexOf(needle) !== -1;
};
Usage:
$.isSubstring("hello world", "world")); // true;
If your limited to jQuery which is just JavaScript... you can use the filter
var subgtSel = $("#jquerySelector").filter(function(i) {
// do your filter here
return $(this).attr("data-timestamp") <= subMsg.CreateDateTimeStamp;
});
the subgtSel
becomes 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.
If your looking for a particular substring... you can do the following with jQuery right in the selector
var sel = $("#jquerySelector:contains('text')");
see http://api.jquery.com/contains-selector/
精彩评论