1

用javascript中的stripos函数,如:

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;
}

我将如何使用/重新编码此函数以匹配特殊字符?

仿佛:

var haystack = 'Le créme';
var needle   = 'reme';
// ^ these two should match (anything other than false)
4

1 回答 1

9

您可以在搜索之前清理字符串

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," ");
}

利用:

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;
}
于 2013-08-14T17:29:17.320 回答