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

1k Views Asked by At

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

2

There are 2 best solutions below

3
shikhar On BEST ANSWER

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

1
Frank Adrian On

You can split your strings to arrays with individual words, which you can filter to find only the words in a string that match your filter string. Here is an example:

var text = value.text.split(' ');
var matchedWords = []
matchedWords = text.filter(res => res.indexOf(filterValue) > -1)

http://jsfiddle.net/brmt0cLj/8/