tags:

views:

52

answers:

4

Is there a "start by" filter in jQuery, something like :contain but with a string beginning condition ?

+1  A: 

I think you can use

indexOf function in javascript

var str = "test string print";

str.indexOf ( "test" ) returns 0

and

str.indexOf ( "print" ) returns 12

So you can check for the return value of indexOf function and if it is 0 then it is at the start position.

rahul
A: 
Start With: ^=

The ^= operator will filter elements whose attribute starts with the given value.

More info here:

http://www.bennadel.com/blog/1003-Cool-jQuery-Predicate-Selectors.htm

http://stackoverflow.com/questions/897025/jquery-return-elements-where-id-begins-with-a-certain-string

Aseem Gautam
These selectors are useful, but they're for attributes, not for content.
Kobi
+2  A: 

Not that I know of, but you can easily implement your own selector for jQuery:

$.extend($.expr[':'], {
    startsWith: function(elem,match) {  
        return (elem.textContent || elem.innerText || "").indexOf(match[3]) == 0;
    }  
});

Now you can use it like this:

$("p:startsWith(Hello)").css("color","red")
duckyflip
Thanks, and with cas insensitive :// case insenstitive for live :contain$.extend($.expr[":"], { "startWith": function(elem, i, match, array) { return (elem.textContent || elem.innerText || "").toLowerCase ().indexOf((match[3] || "").toLowerCase()) == 0; }});
adrien334
A: 

No, but you can do it yourself using filter, as pulse suggested:

$('a').filter(function(){
    return $(this).text().indexOf('start') == 0 }
)

You may want to use a regular expression here, to ignore case, or for more advanced searches:

$('a').filter(function(){
    return $(this).text().match(/^start/i) }
)
Kobi