1

My JSP has following div

<td class="detail">Hello my name is Bond
<br/>James Bond
</td>

I have to search whether the class "detail" has sub string "Bond James Bond"

As Bond James bond has "br" in middle, how can I search that whether this string has the substring

I have tried multiple combinations of /n and br in the jQuery to display

alert($('.detail').text().toLocaleLowerCase().indexOf('bond\n james bond'));

and

 alert($('.detail').text().toLocaleLowerCase().indexOf('bond<br> james bond''));

but it always return -1. help me out thanks in advance

Sunil Kanzar
  • 1,129
  • 1
  • 8
  • 20
Ayush
  • 144
  • 1
  • 17
  • I would first put the result of that call to text() in an alert, so you can see what it is that it will return to you... That might help you figure put what you would need to look for. You may need to use \n\r (or is it \r\n?) for a new line - not sure whether \n will be enough... – moilejter Aug 24 '18 at 07:29

2 Answers2

3

You have two issues here. Firstly the response of text() in this case will remove the <br /> tag in the middle of the element (as it is HTML). Secondly, the removal will leave a lot of blank space and a line break. As a result the output of text will be:

hello my name is bond
      james bond

You can use Regex to remove the line breaks and additional spaces before performing the indexOf() check:

var text = $.trim($('.detail').text()).toLocaleLowerCase().replace(/\s+/g, ' ');

console.log(text.indexOf('bond james bond'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="detail">Hello my name is Bond
      <br/>James Bond
    </td>
  </tr>
</table>
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
0

Use text() to get only the inner text of the td (without any HTML), and then remove all the extra spaces in between.

Then you can simply match it with a Regular Expression created out of your text. See the demo below:

const searchString = 'Bond James Bond';
const regex = new RegExp(searchString);
const text = $('.detail:first').text().replace(/\s+/g, ' ');

console.log(text, '-', regex.test(text));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="detail">Hello my name is Bond
      <br/>James Bond
    </td>
  </tr>
</table>
31piy
  • 21,164
  • 6
  • 40
  • 57