Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs search and ignore spanish characters

Tags:

angularjs

I'm adding a simple sort on a page. The idea is to search products. These products are written in spanish language and has accents. For example: 'Jamón'.

Here is my code:

<div class="form-inline">
  <label>Search</label>
  <input type="text" ng-model="q"/>
</div>

<div ng-repeat="product in products_filtered = (category.products | filter:q | orderBy:'name')">
           ....
</div>

The only problem i have is that you have to type in "Jamón" in order to find the product "Jamón". What I want is to be more flexible, if the user types in "Jamon", the results must include "Jamón".

How can i search with angular filters and forget about accents? Any Idea?

Thanks in advance.

like image 880
Müsli Avatar asked Dec 02 '22 22:12

Müsli


2 Answers

You'll need to create a filter function (or a full filter). This is the simplest thing that could possibly work:

HTML

<div ng-app ng-controller="Ctrl">
    <input type="text" ng-model="search">
    <ul>
        <li ng-repeat="name in names | filter:ignoreAccents">{{ name }}</li>
    </ul>
</div>

Javascript

function Ctrl($scope) {
    function removeAccents(value) {
        return value
            .replace(/á/g, 'a')            
            .replace(/é/g, 'e')
            .replace(/í/g, 'i')
            .replace(/ó/g, 'o')
            .replace(/ú/g, 'u');
    }

    $scope.ignoreAccents = function(item) {               
        if (!$scope.search) return true;       

        var text = removeAccents(item.toLowerCase())
        var search = removeAccents($scope.search.toLowerCase());
        return text.indexOf(search) > -1;
    };

    $scope.names = ['Jamón', 'Andrés', 'Cristián', 'Fernán', 'Raúl', 'Agustín'];
};

jsFiddle here.

Please notice that this only works for arrays of strings. If you want to filter a list of objects (and search in every property of every object, like Angular does) you'll have to enhance the filter function. I think this example should get you started.

like image 152
Michael Benford Avatar answered Feb 08 '23 04:02

Michael Benford


JavaScript has a neat function for this, called localeCompare, where you can specify sensitivity = base, an option that makes it treat á and a as equivalent, but it is not widely supported. I think your only option is to create a filter function wherein you normalise both strings manually (replacing ó with o and so on) and compare the results.

like image 25
Steve Klösters Avatar answered Feb 08 '23 04:02

Steve Klösters