-
Notifications
You must be signed in to change notification settings - Fork 0
/
word-wrap.pipe.ts
58 lines (48 loc) · 1.47 KB
/
word-wrap.pipe.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { Pipe, PipeTransform } from '@angular/core';
/*
* Soft wrap the string in multiple lines using parameter length:
*
* Usage:
* value | wordWrap
* Example:
* 1. In Javascript:
* let wrapString = new WordWrapPipe().transform(string, 30);
*
* 2. In HTML:
* {{ string | wordWrap | 30 }}
*/
@Pipe({name: 'wordWrap'})
export class WordWrapPipe implements PipeTransform {
transform(string: any, charLen:number = 20, delimit: any = '<br/>'): any {
if ( (string == null) || (string.length <= charLen)) {
return string;
}
let result = ' ';
delimit = "<br>";
let newResult = '';
let delimitSpace = '';
let newWordCount = 0;
let words = string.trim().split(/\s+/);
words.forEach( function(word, index) {
let ndwLength = (newResult + delimitSpace + word).length;
if (newResult.length >= (charLen + newWordCount) )
{
result += newResult + delimit;
newResult = '';
newWordCount = 0;
}
if ( ndwLength >= (charLen + newWordCount) ) {
result += newResult + delimit;
newResult = word;
newWordCount = 1;
}
else {
newResult += delimitSpace + word;
newWordCount++;
delimitSpace = ' ';
}
});
result += newResult;
return result;
}
}