-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
format.js
119 lines (96 loc) · 2.1 KB
/
format.js
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
* String format utilities.
*
* @class format
* @namespace util
* @since 2.4.0
* @module hexo
*/
var _ = require('lodash');
/**
* Removes all HTML tags.
*
* @method stripHtml
* @param {String} content
* @return {String}
* @static
*/
exports.strip_html = exports.stripHtml = function(content){
return content.toString().replace(/<[^>]*>/g, '');
};
/**
* Removes whitespace from both ends of the string.
*
* @method trim
* @param {String} content
* @return {String}
* @static
*/
exports.trim = function(content){
return content.toString().trim();
};
/**
* See {% crosslink util.inflector/titleize %}.
*
* @method titlecase
* @param {String} str
* @return {String}
* @static
*/
exports.titlecase = require('./inflector').titlecase;
/**
* Wraps the `text` into lines no longer than `width`.
*
* @method word_wrap
* @param {String} text
* @param {Number} width
* @return {String}
* @static
*/
exports.word_wrap = exports.wordWrap = function(text, width){
width = width || 80;
var arr = [];
for (var i = 0, length = text.length; i < length; i += width){
arr.push(text.substr(i, width));
}
return arr.join('\n');
};
/**
* Truncates the given `text`.
*
* @method truncate
* @param {String} text
* @param {Object} [options]
* @param {Number} [options.length=30]
* @param {String} [options.omission=...]
* @param {String} [options.separator]
* @return {String}
* @static
*/
exports.truncate = function(text, options){
options = _.extend({
length: 30,
omission: '...',
seperator: ''
}, options);
var length = options.length,
omission = options.omission,
separator = options.separator;
if (text.length <= length) return text;
var result = '';
if (separator){
var split = text.split(separator);
for (var i = 0, len = split.length; i < len; i++){
var item = split[i];
if ((result + item + omission).length - 1 <= length){
result += item + ' ';
} else {
break;
}
}
result = result.substring(0, result.length - 1) + omission;
} else {
result = text.substring(0, length - omission.length) + omission;
}
return result;
};