How can I limit content from an API to 15 words (not chars) using Angular 10+?

Viewed 91

I want to limit some content(which it's 50+ words approx) from my API to 15 words , I am trying to make a Pipe but isn't work, the pipes I've found are limit but only characters not words..

I use this:

@Pipe({
  name: 'limitToPipe'
})
export class LimitToPipePipe implements PipeTransform {

  transform(value: string, limit: number): string {
    let trail = '...';

return value.length > limit ? value.substring(0, limit) + trail : value;


 }

}

as I said before, that is not what I want, cause I need to return 15 words and not characters.

can someone help me to do this ? I'm wasted from morning to night trying to do this.

2 Answers

Firstly, just noting that you need to decide exactly what a word is, like: are you including punctuation in your definition of a word; does a hyphenated word count as one or two words...

I haven't checked your code, but it looks like you have the pipe working so just need 15 words? I'd use a regex - something like this:

transform (value: string, words: number): string {
  const regex = new RegExp(`((\\W*\\w+){0,${words}})`);
  const result = value.match(regex)[1];
  return result.length < value.length ? result + '...' : result;
}

The regex is:

((\W*\w+){0,15}})

which matches 0 or more non-word characters '\W+', followed by 1 or more word characters '\w+', then looks for between 0 and 15 matches, taking as many as it can find (in case your initial string has less than 15 words).

If you want to be more specific about which characters to include than \W \w, you can switch them out for explicit character classes. e.g. to add a hyphen to the word characters (to make hyphenated words one word):

transform (value: string, words: number): string {
  const chars='-A-Za-z0-9_';
  const regex = new RegExp(`(([^${chars}]*[${chars}]+){0,${words}})`);
  const result = value.match(regex)[1];
  return result.length < value.length ? result + '...' : result;
}

Building a regex of:

(([^-A-Za-z0-9_]*[-A-Za-z0-9_]+){0,15}})

Cheers,

You can separate the words by splitting them instead of substring. Please check the following code which split the words and returns only the limit specified,

import { Pipe, PipeTransform } from '@angular/core';
    
@Pipe({
   name: 'limitWords'
})
export class LimitWordsPipe implements PipeTransform {
   transform(value: any, limit: any): any {
      return value.length > limit ? value.split(' ').slice(0,limit).join(' ') + '...' :value;
   }
}

App Url - https://limitwordspipe.stackblitz.io
Editor Url - https://stackblitz.com/edit/limitwordspipe?file=src/app/limit-words.pipe.ts

Related