Search code examples
javascriptangularfilterionic2startswith

How filter a word starting with @ form a string in angular 2


I want to filter a @word form a search string. A search string could be milk @company. From that string I would use 'milk' as searchTerm and I need '@company' as another search param. So I can do the following: domain.com/?searchTerm=Milk&Producer=company with an http request.

in my template:

<ion-searchbar [(ngModel)]="searchTerm" (ionInput)="searchResults(searchTerm)" [placeholder]="search" ></ion-searchbar>

the searchResult function:

searchResults() {
    let searchterm = this.searchTerm;
    let producer = // how filter @word? from this.searchTerm string

    this.searchProduct(searchTerm, producer).then(
        data => {
            console.log('data')
        }
    );
}

the call to the api provider:

   public searchProduct(product,producer){
        var sendUrl = `http://example.com/?searchTerm=${product}$producer=${producer}`;
        this.http.get( sendUrl, { headers: new Headers(HEADER.default) })
            .map(res => res.json())
            .subscribe(data => {
                resolve(data);
        });
    }

Solution

  • You can simply use the string split method and use the ‘@‘ as the separator character

    const searchWords = this.searchTerm.split(‘@‘)
    

    This should give you an array with the words.