How to use underscore.string

Comprehensive underscore.string code examples:

How to use underscore.string.lrpad:

978
979
980
981
982
983
984
985
986
987
988


// Aliases
s.strip     = s.trim;
s.lstrip    = s.ltrim;
s.rstrip    = s.rtrim;
s.center    = s.lrpad;
s.rjust     = s.lpad;
s.ljust     = s.rpad;
s.contains  = s.include;
s.q         = s.quote;

How to use underscore.string.toLowerCase:

1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454


},{"./helper/makeString":24}],63:[function(require,module,exports){
var trim = require('./trim');


function boolMatch(s, matchers) {
  var i, matcher, down = s.toLowerCase();
  matchers = [].concat(matchers);
  for (i = 0; i < matchers.length; i += 1) {
    matcher = matchers[i];
    if (!matcher) continue;

How to use underscore.string.default:

46
47
48
49
50
51
52
53
54
55
    return "https://github.com/curedao/curedao-web-android-chrome-ios-app-template.git";
}
exports.getRepoUrl = getRepoUrl;
function getRepoParts() {
    var gitUrl = getRepoUrl();
    gitUrl = underscore_string_1.default.strRight(gitUrl, "github.com/");
    gitUrl = gitUrl.replace(".git", "");
    var parts = gitUrl.split("/");
    if (!parts || parts.length > 2) {
        throw new Error("Could not parse repo name!");

How to use underscore.string.count:

709
710
711
712
713
714
715
716
717
718
//The demo renders grids to terminal automatically, so during each of
//these function calls during the demo (as noted below) a grid is generated...

//var grid = gg.createGrid(3,3)
console.log( grids[0] )
var firstGridDotCount = _s.count( grids[0], '.')
var firstGridEdgeCount = _s.count( grids[0], '[') + _s.count( grids[0], ']')

t.equals( firstGridDotCount , 9, 'There are 9 dots representing 9 blank cells ' )
t.equals( firstGridEdgeCount , 6, 'There are 6 brackets representing 6 edges')

How to use underscore.string.toBool:

How to use underscore.string.cloneDeep:

97
98
99
100
101
102
103
104
105
106
res.locals.fd = function(date, format) {
    return date && moment(new Date(date)).format(format || 'YYYY-MM-DD HH:mm') || '';
};
//自动转换search参数,不带page
res.locals.fsearch = function() {
    var search = _.cloneDeep(req.query.search || req.body.search || {});
    delete search.page;
    return qst.stringify({
        search: search
    });

How to use underscore.string.toNumber:

283
284
285
286
287
288
289
290
291
292
    HawtioBackend.log.debug("requesting hostname: ", hostname);
    next();
});
proxyRouter.param('port', function (req, res, next, port) {
    HawtioBackend.log.debug("requesting port: ", port);
    var portNumber = s.toNumber(port);
    HawtioBackend.log.debug("parsed port number: ", portNumber);
    if (isNaN(portNumber)) {
        res.status(406).send('Invalid port number: "' + port + '"');
    }

How to use underscore.string.rpad:

134
135
136
137
138
139
140
141
142
143
// Build the table
var text = '';
_.each(table, function(row) {
        var i = 0;
        _.each(row, function(col) {
                text += _s.rpad(_s.strip(col), widths[i++], ' ') + '   ';
        });
        text += '\n';
});
return text + '\n';

How to use underscore.string.include:

294
295
296
297
298
299
300
301
302
303
if (w == "(!)") {
  a.push([[w], 0.0, 1.0, 1.0, 1, IRONY]);
}

// EMOTICONS: {("grin", +1.0): set((":-D", ":D"))}
// if ((!w.match(/^[0-9]+$/i)) && (w.length <= 5) && _str.include(PUNCTUATION, w)) {
  Object.keys(EMOTICONS).forEach(function (type) {
    if (_.contains(EMOTICONS[type].e, w.toLowerCase())) {
      a.push([[w], EMOTICONS[type].p, 1.0, 1.0, 1, MOOD]);
    }

How to use underscore.string.reverse:

72
73
74
75
76
77
78
79
80
81
82
/**
 * 返回颠倒的字符串
 * @param str 
 */
function reverseString(str) {
    return _s.reverse(str);
}


/**
 * 

How to use underscore.string.classifye:

39
40
41
42
43
44
45
46
47
48
49
/**
 * 
 * @param str 
 */
function classifye(str) {
    return _s.classifye(str);
}


/**
 * 将下划线或者中划线字符转换成 camelized

How to use underscore.string.swapCase:

23
24
25
26
27
28
29
30
31
32
33
/**
 * 
 * @param str 
 */
function swapCase(str) {
    return _s.swapCase(str);
}


/**
 * 

How to use underscore.string.rtrim:

261
262
263
264
265
266
267
268
269
270
271
272
};


function normalizePath(path) {
    path = _string.ltrim(path, './');
    path = _string.ltrim(path, '/');
    path = _string.rtrim(path, '/');


    return path;
}

How to use underscore.string.map:

985
986
987
988
989
990
991
992
993
994
995
996
s.ljust     = s.rpad;
s.contains  = s.include;
s.q         = s.quote;
s.toBool    = s.toBoolean;
s.camelcase = s.camelize;
s.mapChars  = s.map;




// Implement chaining
s.prototype = {

How to use underscore.string.surround:

10
11
12
13
14
15
16
17
18
19
20
21
22
 */


var utils = new Utils();


utils.backtick = function(field) {
 return field.indexOf(' ') >= 0 ? _str.surround(field, '`') : field;
};


utils.quote = function(outValues, operator, value) {
  if (operator === 'IN' || operator === 'NOT IN') {

How to use underscore.string.splice:

53
54
55
56
57
58
59
60
61
62
sort = {};
var sorts = query.sort.split(QS_VALUE_SPLIT);
for (var i in sorts) {
    var reqSort = sorts[i];
    if (_s.startsWith(reqSort, SORT_REVERSE)) {
        reqSort = _s.splice(reqSort, 0, 1);
        sort[reqSort] = -1;
    } else {
        sort[reqSort] = 1;
    }

How to use underscore.string.unescapeHTML:

388
389
390
391
392
393
394
395
396
397
398
399
400


    let result = txt;


    result = result.replace(/<br\s*[/]?>/gi, brShrink ? ' ' : '\n'); // Заменяем <br> на \n или ничего
    result = _s.stripTags(result); // Убираем обрамляющие тэги ahref
    result = _s.unescapeHTML(result); // Возвращаем эскейпленные


    return result;
};
Utils.txtdiff = (function () {

How to use underscore.string.levenshtein:

32
33
34
35
36
37
38
39
40
41
// Read in the content
var expectedContent = fs.readFileSync('expected/' + filename, 'binary');
var actualContent = fs.readFileSync('actual/' + filename, 'binary');

// Calculate the difference in bits (accounts for random bits)
var difference = _.levenshtein(expectedContent, actualContent);

// Assert that we are under our threshold
var underThreshold = difference <= distance;
assert.ok(underThreshold, 'Bitwise difference of zip files "' + difference + '" should be under ' + distance + ' (' + filename + ')');

How to use underscore.string.cleanDiacritics:

50
51
52
53
54
55
56
57
58
59
	var falseval = args[1] || '';
	return (value === 1 || value === '1' || value == 'actif' || value == 'selected' || value == 'checked' || value == 'erreur') ? trueval : falseval;
},
sanitize: function(value) {
	if (value.length > 120) return value;
	value = _string.cleanDiacritics(value)
		.toLowerCase()
		.replace(/[^a-zA-Z0-9_\.\/]/g, '-')
		.replace(/[_-]+$/g, '-')
		.replace(/-+/g, '-');

How to use underscore.string.chop:

49
50
51
52
53
54
55
56
57
switch(MessageHex.substr(0,12)) { // Look for the first twelve bytes
	case "686400067161":
		hosts.forEach(function(item) {
			item.remote = remote.address;
			item.ready = true;
			payload = "6864002a716100" + item.macAddress + twenties + _s.chop(item.macAddress, 2).reverse().join("") + twenties + "534F43303032FED989D7" + item.state;
			this.sendMessage(hex2ba(payload),remote.address);
			this.emit('discovery', item.index, remote.address);							
		}.bind(this));

How to use underscore.string.decapitalize:

15
16
17
18
19
20
21
22
23
24
25
/**
 * 
 * @param str 
 */
function decapitalize(str) {
    return _s.decapitalize(str);
}


/**
 * 

How to use underscore.string.isBlank:

11
12
13
14
15
16
17
18
19
20
21
22
function isInvalid(value) {
  return lodash.isUndefined(value) || lodash.isNull(value);
}


function isInvalidOrBlank(value) {
  return lodash.isUndefined(value) || lodash.isNull(value) || ustr.isBlank(value);
}


function isValid(value) {
  return !isInvalid(value);

How to use underscore.string.repeat:

72
73
74
75
76
77
78
79
80
81
        }
        return formatText({ raw: result || href, needsSpace: elem.needsSpace }, options);
}

function formatHorizontalLine(elem, fn, options) {
        return '\n' + _s.repeat('-', options.wordwrap) + '\n\n';
}

function formatListItem(prefix, elem, fn, options) {
        options = _.clone(options);

How to use underscore.string.strip:

49
50
51
52
53
54
55
56
57
// - "anchor text" or
// - "href"
function formatAnchor(elem, fn, options) {
        var href = '';
        // Always get the anchor text
        var result = _s.strip(fn(elem.children || [], options));
        if (!result) {
                result = '';
        }

How to use underscore.string.stripTags:

23
24
25
26
27
28
29
30
31
32
);

const body = marked(content);
const title = meta.title ? meta.title : contentProcessors.slugToTitle(slug);
const excerpt = _s.prune(
  _s.stripTags(_s.unescapeHTML(body)),
  config.excerpt_length || 400
);

return {

How to use underscore.string._:

66
67
68
69
70
71
72
73
74
75

// 是否是空白串
console.log(_s.isBlank(' \n\t'));
//=> true

// _s._.join(separator, *strings)
console.log(_s.join('-', 'foo', 'bar', 'baz'));
//=> foo-bar-baz

// 按行拆分成字符串数组

How to use underscore.string.endsWith:

31
32
33
34
35
36
37
38
39
40
41
  this.synset = args.synset;
  this.synsets = {};
  this.labeler = {};
  this.negations = def(args.negations, ["no", "not", "n't", "never"]);
  this.modifiers = def(args.modifiers, ["RB"]);
  this.modifier = def(args.modifier, function (w) { return _str.endsWith(w, "ly"); });
  this.tokenizer = def(args.tokenizer, find_tokens);
}



How to use underscore.string.replaceAll:

74
75
76
77
78
79
80
81
82
83
84
app.use(function* (next) {
    var start = new Date();


    var tags = [];
    var cleanMethod = _s.strLeftBack(this.url, '?');
    cleanMethod = _s.replaceAll(cleanMethod, '/', '_');
    cleanMethod = _s.trim(cleanMethod, '_');
    cleanMethod = this.method + '.' + cleanMethod;
    cleanMethod = cleanMethod.toLowerCase();
    tags.push('endpoint:' + cleanMethod);

How to use underscore.string.toBoolean:

5
6
7
8
9
10
11
12
13
14
function isNumber(x) {
  return x.length > 0 && !isNaN(x);
}

function isBoolean(x) {
  return s.toBoolean(x) !== undefined;
}

module.exports.run = function(command, str, args) {
  return R.apply(

How to use underscore.string.strRight:

223
224
225
226
227
228
229
230
231
232
}
separateValueUnit(string) {
    var str = _s.clean(string);
    if (_s.contains(str, ' ')) {
        var value = _s.strLeft(str, ' ');
        var unit = _s.strRight(str, ' ');
    }
    else {
        var value = str;
    }