![](/img/trans.png)
[英]How can I use the BroadcastChannel API or something similar in Safari 10+?
[英]How can I limit content from an API to 15 words (not chars) using Angular 10+?
我想將我的 API 中的一些內容(大約 50 多個單詞)限制為 15 個單詞,我正在嘗試制作 Pipe 但不起作用,我發現的管道是有限的,但只有字符而不是單詞。
我用這個:
@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;
}
}
正如我之前所說,這不是我想要的,因為我需要返回 15 個單詞而不是字符。
有人可以幫我這樣做嗎? 我從早到晚都在浪費時間嘗試這樣做。
首先,請注意您需要准確確定一個單詞是什么,例如:您是否在單詞定義中包含標點符號? 帶連字符的單詞算一兩個單詞嗎...
我沒有檢查你的代碼,但看起來你有 pipe 工作所以只需要 15 個字? 我會使用正則表達式 - 像這樣:
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;
}
正則表達式是:
((\W*\w+){0,15}})
它匹配 0 個或多個非單詞字符 '\W+',后跟 1 個或多個單詞字符 '\w+',然后查找 0 到 15 個匹配項,盡可能多地查找(以防您的初始字符串具有較少超過 15 個字)。
如果您想比 \W \w 更具體地確定要包含的字符,您可以將它們切換為顯式字符類。 例如為單詞字符添加連字符(使連字符變成一個單詞):
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;
}
構建一個正則表達式:
(([^-A-Za-z0-9_]*[-A-Za-z0-9_]+){0,15}})
干杯,
您可以通過拆分單詞而不是 substring 來分隔單詞。 請檢查以下代碼,該代碼拆分單詞並僅返回指定的限制,
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;
}
}
應用程序 Url - https://limitwordspipe.stackblitz.io
編輯器 Url - https://stackblitz.com/edit/limitwordspipe?file=src/app/limit-words.pipe.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.