Home > front end >  javascript includes() problems
javascript includes() problems

Time:12-10

var needle = "şebo yağmurlar"

var haystack = {
  "items": [{
    "song": "Yağmurlar",
    "artist": "blah"
  }, {
    "song": "Yağmur",
    "artist": "blah"
  }]
}

var found = haystack.items.find(
  item => 
  needle.includes(item.song.toLocaleLowerCase('tr-TR'))) 
  || needle.includes(item.artist.toLocaleLowerCase('tr-TR'))

i have two songs in json. "Yağmur" and "Yağmurlar" but they are searching it like "blah blah yağmurlar" or "blah blah yağmur" or exact "yağmur" "yağmurlar". includes always find "Yağmur" song on my side

input => "blah blah yağmurlar"
result => yağmur song
expect => yağmurlar

CodePudding user response:

Your original problem

Make sure the key in haystack matches the key you are searching for. Your haystack contains the key song, but your find is looking for the key title.

Try this:

var needle = "şebo yağmurlar"

var haystack = {
  "items": [{
    "song": "Yağmurlar",
    "artist": "blah"
  }, {
    "song": "Yağmur",
    "artist": "blah"
  }]
}

var found = haystack.items.find(
  item => 
  needle.includes(item.song.toLocaleLowerCase('tr-TR'))) 
  || needle.includes(item.artist.toLocaleLowerCase('tr-TR'))

console.log(found)

Your updated problem

let text = "Hello world, yağmurlar to the universe.";
let search = "Yağmur";
let result = text.includes(search.toLocaleLowerCase('tr-TR'));

If you want the answer to be false, then don't do a "toLocaleLowerCase":

let result = text.includes(search);

Third problem: to reverse the search pattern.

From your comments I think you are trying to say that you WANT there to be no match in the example you provide. (If that is not your intention, please list examples of input, and what you want the output to be.)

var needle = "şebo yağmurlar"

var haystack = {
  "items": [{
    "song": "Yağmurlar",
    "artist": "blah"
  }, {
    "song": "Yağmur",
    "artist": "blah"
  }]
}

var found = haystack.items.find(
  item =>
  item.song.toLocaleLowerCase('tr-TR').includes(needle.toLocaleLowerCase('tr-TR')) ||
  item.artist.toLocaleLowerCase('tr-TR').includes(needle.toLocaleLowerCase('tr-TR'))
)

console.log(found)

  • Related