简体   繁体   中英

check if a string exist in a div text jquery

 var qtr = $('div').text(); var qtr1 = qtr.split(',') console.log(qtr1.length) for (var i = 0; i < qtr1.length; i++) { console.log(qtr1[i]); } console.log(qtr1); if ($.inArray('1st qtr', qtr1)) { alert('1st'); } if ($.inArray('2nd qtr', qtr1)) { alert('2nd'); } if ($.inArray('3rd qtr', qtr1)) { alert('3rd'); } if ($.inArray('4th qtr', qtr1)) { alert('4th'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div>1st qtr,2nd qtr,3rd qtr,4th qtr,</div> 

I have a div with text in it i want to check if a specific text is in the div. I tried splitting the div text and getting checking $.inArray but the first text is not being shown even if it is missing.

Problem:

  1. Why do i get 5 as length in even if there are only 4 text. An extra space is being added at the last
  2. Why is the first text which is 1st qtr not shown even if it is existing.
  3. What is the best to check if a text is existing in a text .

Why do i get 5 as length in even if there are only 4 text. An extra space is being added at the last

The string contains , at the end. When the string is split using , , an empty string is added as the last element since there is nothing after the last , . You can remove the last , by using regex.

Why is the first text which is 1st qtr now shown even if it is existing.

The inArray returns the index of the sub-string found in the string. So, for the first string the index 0 is returned. As 0 is falsy value, the if condition is evaluate to false and the block is not executed.

Updated Code

 var qtr = $('div').text().replace(/,$/, ''); var qtr1 = qtr.split(','); console.log(qtr1.length) if ($.inArray('1st qtr', qtr1) !== -1) { alert('1st'); } if ($.inArray('2nd qtr', qtr1) !== -1) { alert('2nd'); } if ($.inArray('3rd qtr', qtr1) !== -1) { alert('3rd'); } if ($.inArray('4th qtr', qtr1) !== -1) { alert('4th'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div>1st qtr,2nd qtr,3rd qtr,4th qtr,</div> 

What is the best to check if a text is existing in a text.

indexOf is the best to check if the string contains a substring

 var str = '1st qtr,2nd qtr,3rd qtr,4th qtr,'; var contains = str.indexOf('4th qtr') > -1; alert('str contains 4th qtr? ' + contains); 

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