Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .text() cannot use indexOf to find spaces

This is an odd one.

I have a list item, containing the text '13 May 2011'. I have a lot of these dates, and I want to use JQuery to search them by a free text input (they're not always dates), but I can't seem to search for anything if I put a space in the search box.

However,

li.text() // 13 May 2011
li.text().indexOf('13') // 0
li.text().indexOf('13 ') // -1
li.text().indexOf(' ') // -1
'13 May 2011'.indexOf('13') // 0
'13 May 2011'.indexOf('13 ') // 0
li.text() == '13 May 2011' // false

I've pasted my return text into a text-to-hex converter, and the space character is a '20' (32 in decimal, which is a space in ASCII), so it's not a funny space character.

Has anyone encountered this problem before? Does anyone have any other ideas?

like image 350
Connell Avatar asked Jun 23 '11 14:06

Connell


People also ask

How do I check if a string has a space?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.

How do you check if there are spaces in a string Javascript?

To check if a string contains only spaces, use the test() method with the following regular expression /^\s*$/ . The test method will return true if the string contains only spaces and false otherwise.

What is indexOf() in js?

The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.

How to get the text of element in jQuery?

To set or get the text value of input or textarea elements, use the . val() method. To get the value of a script element, use the . html() method.


1 Answers

Answering my own question. Thanks to all those that helped me along the way by leaving comments!

All tests with this list item have worked as they should except the real version on my machine! For some reason, it's not a space, it's ASCII character 160 (a non-breaking space, HTML entity  )

Further investigation shows

hex(li.text()) // 31 33 a0 4d 61 79 a0 32 30 31 31
li.text().indexOf('13'+String.fromCharCode(160)) // 0

I'm not going to question why, at least it works now :D

like image 89
Connell Avatar answered Nov 01 '22 13:11

Connell