Search code examples
angularjsangularjs-ng-repeatangularjs-filter

AngularJS filter show only matched word as result, not entire string


Is it possible to display only the matched word in ng-repeat with filters?

For example I have the following strings

[
{text: 'This is first text from the array.'},
{text: 'Text in this array is dummy and it makes no sense'}, 
{text: 'AngularJS is very old framework'}
]

If I search for characters "fr", then I want in my list to display only ti elements: "from" from the first string and "framework" from the last string in the array. I don't need to display the entire string.

Result should be for example:

<li>from</li>
<li>framework</li>

In filter service, I tried to update the {text:} value to be equal to the match value, but it updates the original array of objects;

Here is my JSFiddle Filter Example JSFiddle


Solution

  • Its not nice but you can try this, its almost giving what you want. I would suggest you to render the search in other ng-repeat block that can be neat and efficient.

    items.filter(list => {
            if (list.text.toLowerCase().includes(filterValue)) {
              let catchPattern = new RegExp('(\\w*' + filterValue + '\\w*)', 'gi');
              let matches = list.text.toLowerCase().match(catchPattern)
              if (!matches)
                return items;
    
              filterdArray.push({
                'text': matches,
                'id': list.id
              })
            }
    
          });
    

    Attached fiddle for the same: Find Word from the string