简体   繁体   中英

Check for a specific character in a string

How can I check for a specific character in a element?

<div>N0180/RIB</div>
<div>N0180918</div>
<div>N0180</div>

**(I want to target <div>N0180</div> this element)**

I tried to use :contains("N0180") and .substring method. But it is target all three elements.

As per :contains() Doc:

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains() can be written as a bare word or surrounded by quotation marks. The text must have matching case to be selected.

You can rather use .filter() for more specific comparison :

$('div').filter(function(){
   return $(this).text().trim() === "N0180";
})

For exact match use .filter()

$('div').filter(function(){
    return $(this).text().trim() == "N0180";
})

Note: For case-insensitive search convert the values to same cases using toLowerCase() or .toUpperCase()

 $('div').each(function() { if ($(this).text() === 'N0180') { $(this).addClass('red') } }) 
 .red { color: red } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>N0180/RIB</div> <div>N0180918</div> <div>N0180</div> 

You can get the .text() of div and compare to your text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM