Reputation: 6509
I'm changing the background via CSS if the text "Off" is found. Works fine.
$('td:contains("Off")').filter(function() {
return $(this).text() == "Off";
}).css({"background":"#667881", "color":"white"});
Is there a way to amend the jQuery .filter function above to only test the first 3 characters (capturing only 'Off')? Some of textfields contain more:
"Off some more words"
Ones like these aren't targeted via my code above even though they contain 'Off'
However, I don't want ones like this to be targeted: "some more words Off"
Upvotes: 0
Views: 119
Reputation: 115242
You can use match()
with regex ^Off
, which only matches string start with Off
$('td').filter(function() {
return $(this).text().match(/^Off/);
}).css({
"background": "#667881",
"color": "white"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>Off
</td>
<td>omff
</td>
<td>off
</td>
<td>coff
</td>
</tr>
</table>
Upvotes: 2
Reputation: 99
Why not just use $(this).text().substring(0,3)?
It's not a filter functionality but it should do the job.
Hope it helps! :)
Upvotes: 1
Reputation: 207983
Use match():
$('td:contains("Off")').filter(function() {
return $(this).text().match("^Off");
}).css({"background":"#667881", "color":"white"});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>Off some more words</td>
</tr>
<tr>
<td>some more words Off</td>
</tr>
<tr>
<td>some more Off words Off</td>
</tr>
</table>
The ^
matches only if the text begins with Off
Upvotes: 2
Reputation: 8523
You can add a substring to your $(this).text()
in the filter function, like so
$('td').filter(function() {
return $(this).text().substring(0,3) == "Off";
}).css({"background":"#667881", "color":"white"});
Upvotes: 3