So, I am testing the JS includes() method, so I created a search input field, where I can search through the notes I created with live rerendering. Now my question is: When I pass no searchtext at all, all the notes are shown, but when I enter a character or a word, the notes get filtered right away. Example code:
const filters = {
searchText: ''
}
// Render application notes
const renderNotes = (notes, filters) => {
const filteredNotes = notes.filter((note) => {
return note.title.toLowerCase().includes(filters.searchText.toLowerCase())
})
document.querySelector('#notes').innerHTML = ''
filteredNotes.forEach((note) => {
const noteEl = generateNoteDOM(note)
document.querySelector('#notes').appendChild(noteEl)
})
}
I understand from this, that true is always returned in such a case.. Would appreciate any clarification to this subject!
Thanks!
So, I am testing the JS includes() method, so I created a search input field, where I can search through the notes I created with live rerendering. Now my question is: When I pass no searchtext at all, all the notes are shown, but when I enter a character or a word, the notes get filtered right away. Example code:
const filters = {
searchText: ''
}
// Render application notes
const renderNotes = (notes, filters) => {
const filteredNotes = notes.filter((note) => {
return note.title.toLowerCase().includes(filters.searchText.toLowerCase())
})
document.querySelector('#notes').innerHTML = ''
filteredNotes.forEach((note) => {
const noteEl = generateNoteDOM(note)
document.querySelector('#notes').appendChild(noteEl)
})
}
I understand from this, that true is always returned in such a case.. Would appreciate any clarification to this subject!
Thanks!
Share Improve this question edited Jul 30, 2018 at 14:29 mplungjan 178k28 gold badges180 silver badges240 bronze badges asked Jul 30, 2018 at 14:25 MichaelMichael 9877 silver badges18 bronze badges 2- Is that not the expected and preferred solution? – mplungjan Commented Jul 30, 2018 at 14:27
- yes it is, I was just wondering, if my logic is right... :) – Michael Commented Jul 30, 2018 at 14:41
2 Answers
Reset to default 19The .includes()
function has to match the functionality of .indexOf()
for consistency, and .indexOf()
always matches the empty string in any target string. From MDN:
An empty string searchValue will match at any index between 0 and str.length.
It's a little counter-intuitive, but consider this:
var str = "something";
console.log(str.includes("")); // Imagine this returns false ...
str += "";
console.log(str.includes("")); // !!
I would suggest adding your own version of .includes()
as below
String.prototype.includes = function(subStr) {
if (subStr.length == 0 || this.indexOf(subStr) === -1 ) {
return false;
}
return true;
};
var name = "JavaScript";
console.log(name.includes("")); // false
console.log(name.includes(" ")); // false
console.log(name.includes("J")); // true