如何强制我的搜索输入字段忽略非拉丁字符? [英] How can i force my search input field to ignore non latin characters?

查看:88
本文介绍了如何强制我的搜索输入字段忽略非拉丁字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jquery为我的网站构建搜索过滤器功能.它与拉丁字符很好用,但是当我尝试搜索非拉丁字符(例如瑞典语单词)时,它不起作用.

I am trying to build a search filter function for my website using jquery. It works pretty well with Latin characters but when i try to search for non Latin characters like for example Swedish words it doesn't work.

这是我使用的代码:

$('#box').keyup(function() {
  var valThis = $(this).val().toLowerCase();
  if (valThis == "") {
    $('.navList > li').show();
  } else {
    $('.navList > li').each(function() {
      var text = $(this).text().toLowerCase();
      (text.indexOf(valThis) >= 0) ? $(this).show(): $(this).hide();
    });
  };
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Search Me" id="box" type="text" />
<ul class="navList">
  <li>människa</li>
  <li>träd</li>
  <li>acai</li>
  <li>blueberry</li>
  <li>bananas</li>
  <li>cherry</li>
  <li>coconut</li>
  <li>donut</li>
  <li>durean</li>
</ul>

请注意,列表中的前两个单词是瑞典语单词.我要做的是使搜索功能忽略瑞典字母ä",并将其与拉丁字母"a"相同.

Notice the 2 first words in the list are Swedish words. What i want to do is to make the search function to ignore the Swedish letters "ä" and treat them same with the Latin letter "a".

为了更清楚一点,我只想强制搜索功能将字母ä"和"a"视为相同.因此,当您开始输入..."ma"或mä"来显示单词människa"

And just to make it more clear, i just want to force the search function to treat both letters "ä" and "a" as the same. So when you start typing... "ma" or "mä" to display the word "människa"

我在 JSFIDDLE

推荐答案

如果您知道等效的字母,则可以为每个要替换的字母创建一个映射.我已经更新了小提琴,请检查.

If you know the equivalent letters, then you can create a map for each letter to be replaced. I have updated the fiddle please check.

var langMap = {
  'a': 'ä'
}

$('#box').keyup(function() {
  var valThis = $(this).val().toLowerCase();
  var filteredWord = valThis.split('').map(function(letter) {
    if (langMap[letter]) {
      return langMap[letter];
    }
    return letter;
  }).join('');

  if (filteredWord == "") {
    $('.navList > li').show();
  } else {
    $('.navList > li').each(function() {
      var text = $(this).text().toLowerCase();
      (text.indexOf(filteredWord) >= 0) ? $(this).show(): $(this).hide();
    });
  };
});

这篇关于如何强制我的搜索输入字段忽略非拉丁字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆