1

With a stripos function in javascript, such as:

function stripos (f_haystack, f_needle, f_offset) {
  var haystack = (f_haystack + '').toLowerCase();
  var needle = (f_needle + '').toLowerCase();
  var index = 0;

  if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
    return index;
  }
  return false;
}

How would I use/recode this function so that it matches special characters?

As if:

var haystack = 'Le créme';
var needle   = 'reme';
// ^ these two should match (anything other than false)
Frantisek
  • 7,485
  • 15
  • 59
  • 102
  • create an array that associates special characters to normal charaters, then when doing your match, replace special characters with their non-special equivalents. An example can be found here: http://jqueryui.com/autocomplete/#folding – Kevin B Aug 14 '13 at 15:41
  • The answer is answered here https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript but please be sure to scroll down because the accepted answer isn't current. My answer is 3rd I believe and should be preferred. – Lewis Diamond Jul 11 '17 at 14:36

1 Answers1

10

you can clean the strings before the search

String.prototype.removeAccents = function(){
 return this
         .replace(/[áàãâä]/gi,"a")
         .replace(/[éè¨ê]/gi,"e")
         .replace(/[íìïî]/gi,"i")
         .replace(/[óòöôõ]/gi,"o")
         .replace(/[úùüû]/gi, "u")
         .replace(/[ç]/gi, "c")
         .replace(/[ñ]/gi, "n")
         .replace(/[^a-zA-Z0-9]/g," ");
}

use:

function stripos (f_haystack, f_needle, f_offset) {
  var haystack = (f_haystack + '').toLowerCase().removeAccents();
  var needle = (f_needle + '').toLowerCase().removeAccents();
  var index = 0;

  if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
    return index;
  }
  return false;
}
Luan Castro
  • 1,184
  • 7
  • 14