Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript string.prototype.contains() with locale

Is it posible to check if a string contains a substring with locale support?

'Ábc'.contains('A') should be true.

Javascript now has the string.prototype.localeCompare() for string comparison with locale support but I cannot see the localeContains() counterpart.

like image 237
David Casillas Avatar asked Sep 17 '16 15:09

David Casillas


Video Answer


1 Answers

There is a faster alternative to contains() with locale check on string

It seems that to strip diacritics and then natively compare the strings is much faster: on my architecture almost 10 times faster than @chickens or @dag0310 solution, check yours here. Returns true on empty string check to be consistent with String.includes.

String.prototype.localeContains = function(sub) {
  if(sub==="") return true;
  if(!sub || !this.length) return false;
  sub = ""+sub;
  if(sub.length>this.length) return false;
  let ascii = s => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
  return ascii(this).includes(ascii(sub));
}

var str = "142 Rozmočených Kříd";
console.log(str.localeContains("kŘi"));
console.log(str.localeContains(42));
console.log(str.localeContains(""));
console.log(str.localeContains(false));
like image 66
Jan Turoň Avatar answered Sep 19 '22 12:09

Jan Turoň