move functions to commonjs modules

closes #355
pull/357/head
Christoph Hermann 9 years ago
parent eb7dfee89f
commit f3d973518d

1
.gitignore vendored

@ -3,3 +3,4 @@
.project
.tmp_*
node_modules
underscore.string.compiled.js

@ -1,8 +1,3 @@
language: node_js
node_js:
- "0.11"
before_script:
- "export DISPLAY=:99.0"
- "sh -e /etc/init.d/xvfb start"
- sleep 2

@ -22,7 +22,7 @@ _(" epeli ").chain().trim().capitalize().value()
## Download ##
* [Development version](https://raw.github.com/epeli/underscore.string/master/lib/underscore.string.js) *Uncompressed with Comments 18kb*
* [Development version](https://raw.github.com/epeli/underscore.string/master/underscore.string.js) *Uncompressed with Comments 18kb*
* [Production version](https://github.com/epeli/underscore.string/raw/master/dist/underscore.string.min.js) *Minified 7kb*
@ -38,6 +38,16 @@ _(" epeli ").chain().trim().capitalize().value()
var _s = require('underscore.string');
```
**Import specific modules (browserify/node)**:
```javascript
var capitalize = require('underscore.string/capitalize');
var trim = require('underscore.string/trim');
capitalize(trim(" epeli "));
=> "Epeli"
```
**Integrate with Underscore.js**:
```javascript

@ -17,7 +17,7 @@
"underscore",
"string"
],
"main": "./lib/underscore.string.js",
"main": "./underscore.string.js",
"repository": {
"type": "git",
"url": "https://github.com/epeli/underscore.string.git"

@ -0,0 +1,7 @@
var trim = require('./trim');
module.exports = function camelize(str) {
return trim(str).replace(/[-_\s]+(.)?/g, function(match, c) {
return c ? c.toUpperCase() : "";
});
};

@ -0,0 +1,6 @@
var makeString = require('./helper/makeString');
module.exports = function capitalize(str) {
str = makeString(str);
return str.charAt(0).toUpperCase() + str.slice(1);
};

@ -0,0 +1,5 @@
var makeString = require('./helper/makeString');
module.exports = function chars(str) {
return makeString(str).split('');
};

@ -0,0 +1,6 @@
module.exports = function chop(str, step) {
if (str == null) return [];
str = String(str);
step = ~~step;
return step > 0 ? str.match(new RegExp('.{1,' + step + '}', 'g')) : [str];
};

@ -0,0 +1,6 @@
var capitalize = require('./capitalize');
var camelize = require('./camelize');
module.exports = function classify(str) {
return capitalize(camelize(String(str).replace(/[\W_]/g, ' ')).replace(/\s/g, ''));
};

@ -0,0 +1,5 @@
var trim = require('./trim');
module.exports = function clean(str) {
return trim(str).replace(/\s+/g, ' ');
};

@ -6,6 +6,6 @@
"keywords": ["underscore", "string"],
"dependencies": {},
"development": {},
"main": "lib/underscore.string.js",
"scripts": ["lib/underscore.string.js"]
"main": "underscore.string.js",
"scripts": ["underscore.string.js"]
}

@ -0,0 +1,19 @@
var makeString = require('./helper/makeString');
module.exports = function(str, substr) {
str = makeString(str);
substr = makeString(substr);
var count = 0,
pos = 0,
length = substr.length;
while (true) {
pos = str.indexOf(substr, pos);
if (pos === -1) break;
count++;
pos += length;
}
return count;
};

@ -0,0 +1,5 @@
var trim = require('./trim');
module.exports = function dasherize(str) {
return trim(str).replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase();
};

@ -0,0 +1,6 @@
var makeString = require('./helper/makeString');
module.exports = function decapitalize(str) {
str = makeString(str);
return str.charAt(0).toLowerCase() + str.slice(1);
};

@ -0,0 +1,13 @@
var makeString = require('./helper/makeString');
var toPositive = require('./helper/toPositive');
module.exports = function endsWith(str, ends, position) {
str = makeString(str);
ends = '' + ends;
if (typeof position == 'undefined') {
position = str.length - ends.length;
} else {
position = Math.min(toPositive(position), str.length) - ends.length;
}
return position >= 0 && str.indexOf(ends, position) === position;
};

@ -0,0 +1,12 @@
var makeString = require('./helper/makeString');
var escapeChars = require('./helper/escapeChars');
var reversedEscapeChars = {};
for(var key in escapeChars) reversedEscapeChars[escapeChars[key]] = key;
reversedEscapeChars["'"] = '#39';
module.exports = function escapeHTML(str) {
return makeString(str).replace(/[&<>"']/g, function(m) {
return '&' + reversedEscapeChars[m] + ';';
});
};

@ -0,0 +1,10 @@
module.exports = function() {
var result = {};
for (var prop in this) {
if (!this.hasOwnProperty(prop) || prop.match(/^(?:include|contains|reverse)$/)) continue;
result[prop] = this[prop];
}
return result;
};

@ -1,50 +1,62 @@
var gulp = require('gulp-param')(require('gulp'), process.argv),
qunit = require("gulp-qunit"),
uglify = require('gulp-uglify'),
clean = require('gulp-clean'),
bump = require('gulp-bump'),
replace = require('gulp-replace'),
rename = require('gulp-rename'),
SRC = 'lib/underscore.string.js',
DEST = 'dist',
MIN_FILE = 'underscore.string.min.js',
TEST_SUITES = ['test/test.html', 'test/test_underscore/index.html'],
VERSION_FILES = ['./package.json', './component.json'];
qunit = require("gulp-qunit"),
uglify = require('gulp-uglify'),
clean = require('gulp-clean'),
bump = require('gulp-bump'),
replace = require('gulp-replace'),
rename = require('gulp-rename'),
browserify = require('gulp-browserify'),
SRC = 'underscore.string.js',
SRC_COMPILED = 'underscore.string.compiled.js',
DEST = 'dist',
MIN_FILE = 'underscore.string.min.js',
TEST_SUITES = ['test/test.html', 'test/test_standalone.html', 'test/test_underscore/index.html'],
VERSION_FILES = ['./package.json', './component.json'];
gulp.task('test', function() {
return gulp.src(TEST_SUITES)
.pipe(qunit());
gulp.task('test', ['browserify'], function() {
return gulp.src(TEST_SUITES)
.pipe(qunit());
});
gulp.task('browserify', function() {
return gulp.src(SRC)
.pipe(browserify({
detectGlobals: true,
standalone: 'underscore.string'
}))
.pipe(rename('underscore.string.compiled.js'))
.pipe(gulp.dest('./'));
});
gulp.task('clean', function() {
return gulp.src(DEST)
.pipe(clean());
return gulp.src(DEST)
.pipe(clean());
});
gulp.task('bump-in-js', function(semver) {
gulp.src(SRC)
.pipe(replace(/(version:?\s\')([\d\.]*)\'/gi, '$1' + semver + "'"))
.pipe(gulp.dest('./lib'));
return gulp.src(SRC)
.pipe(replace(/(version:?\s\')([\d\.]*)\'/gi, '$1' + semver + "'"))
.pipe(gulp.dest('./'));
});
// usage: gulp bump -s <% Version %>
// usage: gulp bump --semver <% Version %>
gulp.task('bump', ['bump-in-js'], function(semver) {
if (typeof semver !== 'string' || semver.length <= 0) {
console.error('pass a new version `gulp bump --semver 2.4.1`');
process.exit(1);
}
if (typeof semver !== 'string' || semver.length <= 0) {
console.error('pass a new version `gulp bump --semver 2.4.1`');
process.exit(1);
}
return gulp.src(VERSION_FILES)
.pipe(bump({
version: semver
}))
.pipe(gulp.dest('./'));
return gulp.src(VERSION_FILES)
.pipe(bump({
version: semver
}))
.pipe(gulp.dest('./'));
});
gulp.task('build', ['test', 'clean'], function() {
return gulp.src(SRC)
.pipe(uglify())
.pipe(rename(MIN_FILE))
.pipe(gulp.dest(DEST));
return gulp.src(SRC_COMPILED)
.pipe(uglify())
.pipe(rename(MIN_FILE))
.pipe(gulp.dest(DEST));
});

@ -0,0 +1,10 @@
var escapeRegExp = require('./escapeRegExp');
module.exports = function defaultToWhiteSpace(characters) {
if (characters == null)
return '\\s';
else if (characters.source)
return characters.source;
else
return '[' + escapeRegExp(characters) + ']';
};

@ -0,0 +1,9 @@
var escapeChars = {
lt: '<',
gt: '>',
quot: '"',
amp: '&',
apos: "'"
};
module.exports = escapeChars;

@ -0,0 +1,5 @@
var makeString = require('./makeString');
module.exports = function escapeRegExp(str) {
return makeString(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};

@ -0,0 +1,7 @@
/**
* Ensure some object is a coerced to a string
**/
module.exports = function makeString(object) {
if (object == null) return '';
return '' + object;
};

@ -0,0 +1,9 @@
module.exports = function strRepeat(str, qty){
if (qty < 1) return '';
var result = '';
while (qty > 0) {
if (qty & 1) result += str;
qty >>= 1, str += str;
}
return result;
};

@ -0,0 +1,3 @@
module.exports = function toPositive(number) {
return number < 0 ? 0 : (+number || 0);
};

@ -0,0 +1,6 @@
var capitalize = require('./capitalize');
var underscored = require('./underscored');
module.exports = function humanize(str) {
return capitalize(underscored(str).replace(/_id$/, '').replace(/_/g, ' '));
};

@ -0,0 +1,6 @@
var makeString = require('./helper/makeString');
module.exports = function include(str, needle) {
if (needle === '') return true;
return makeString(str).indexOf(needle) !== -1;
};

@ -0,0 +1,5 @@
var splice = require('./splice');
module.exports = function insert(str, i, substr) {
return splice(str, i, 0, substr);
};

@ -0,0 +1,5 @@
var makeString = require('./helper/makeString');
module.exports = function isBlank(str) {
return (/^\s*$/).test(makeString(str));
};

@ -0,0 +1,9 @@
var makeString = require('./helper/makeString');
var slice = [].slice;
module.exports = function join() {
var args = slice.call(arguments),
separator = args.shift();
return args.join(makeString(separator));
};

@ -0,0 +1,25 @@
var makeString = require('./helper/makeString');
module.exports = function levenshtein(str1, str2) {
str1 = makeString(str1);
str2 = makeString(str2);
var current = [],
prev, value;
for (var i = 0; i <= str2.length; i++)
for (var j = 0; j <= str1.length; j++) {
if (i && j)
if (str1.charAt(j - 1) === str2.charAt(i - 1))
value = prev;
else
value = Math.min(current[j], current[j - 1], prev) + 1;
else
value = i + j;
prev = current[j];
current[j] = value;
}
return current.pop();
};

@ -1,659 +0,0 @@
// Underscore.string
// (c) 2010 Esa-Matti Suuronen <esa-matti aet suuronen dot org>
// Underscore.string is freely distributable under the terms of the MIT license.
// Documentation: https://github.com/epeli/underscore.string
// Some code is borrowed from MooTools and Alexandru Marasteanu.
// Version '2.4.0'
!function(root, String){
'use strict';
// Defining helper functions.
var nativeTrim = String.prototype.trim;
var nativeTrimRight = String.prototype.trimRight;
var nativeTrimLeft = String.prototype.trimLeft;
var parseNumber = function(source) { return source * 1 || 0; };
var strRepeat = function(str, qty){
if (qty < 1) return '';
var result = '';
while (qty > 0) {
if (qty & 1) result += str;
qty >>= 1, str += str;
}
return result;
};
var slice = [].slice;
var toString = Object.prototype.toString;
// Ensure some object is a coerced to a string
function makeString(object) {
if (object == null) return '';
return '' + object;
}
var defaultToWhiteSpace = function(characters) {
if (characters == null)
return '\\s';
else if (characters.source)
return characters.source;
else
return '[' + _s.escapeRegExp(characters) + ']';
};
// Helper for toBoolean
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;
if (matcher.test && matcher.test(s)) return true;
if (matcher.toLowerCase() === down) return true;
}
}
function toPositive(number) {
return number < 0 ? 0 : (+number || 0);
}
var escapeChars = {
lt: '<',
gt: '>',
quot: '"',
amp: '&',
apos: "'"
};
var reversedEscapeChars = {};
for(var key in escapeChars) reversedEscapeChars[escapeChars[key]] = key;
reversedEscapeChars["'"] = '#39';
// sprintf() for JavaScript 0.7-beta1
// http://www.diveintojavascript.com/projects/javascript-sprintf
//
// Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
// All rights reserved.
var sprintf = (function() {
function get_type(variable) {
return toString.call(variable).slice(8, -1).toLowerCase();
}
var str_repeat = strRepeat;
var str_format = function() {
if (!str_format.cache.hasOwnProperty(arguments[0])) {
str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
}
return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
};
str_format.format = function(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
for (i = 0; i < tree_length; i++) {
node_type = get_type(parse_tree[i]);
if (node_type === 'string') {
output.push(parse_tree[i]);
}
else if (node_type === 'array') {
match = parse_tree[i]; // convenience purposes only
if (match[2]) { // keyword argument
arg = argv[cursor];
for (k = 0; k < match[2].length; k++) {
if (!arg.hasOwnProperty(match[2][k])) {
throw new Error(sprintf('[_.sprintf] property "%s" does not exist', match[2][k]));
}
arg = arg[match[2][k]];
}
} else if (match[1]) { // positional argument (explicit)
arg = argv[match[1]];
}
else { // positional argument (implicit)
arg = argv[cursor++];
}
if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
throw new Error(sprintf('[_.sprintf] expecting number but found %s', get_type(arg)));
}
switch (match[8]) {
case 'b': arg = arg.toString(2); break;
case 'c': arg = String.fromCharCode(arg); break;
case 'd': arg = parseInt(arg, 10); break;
case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
case 'o': arg = arg.toString(8); break;
case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
case 'u': arg = Math.abs(arg); break;
case 'x': arg = arg.toString(16); break;
case 'X': arg = arg.toString(16).toUpperCase(); break;
}
arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
pad_length = match[6] - String(arg).length;
pad = match[6] ? str_repeat(pad_character, pad_length) : '';
output.push(match[5] ? arg + pad : pad + arg);
}
}
return output.join('');
};
str_format.cache = {};
str_format.parse = function(fmt) {
var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
while (_fmt) {
if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
}
else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
parse_tree.push('%');
}
else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
var field_list = [], replacement_field = match[2], field_match = [];
if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else {
throw new Error('[_.sprintf] huh?');
}
}
}
else {
throw new Error('[_.sprintf] huh?');
}
match[2] = field_list;
}
else {
arg_names |= 2;
}
if (arg_names === 3) {
throw new Error('[_.sprintf] mixing positional and named placeholders is not (yet) supported');
}
parse_tree.push(match);
}
else {
throw new Error('[_.sprintf] huh?');
}
_fmt = _fmt.substring(match[0].length);
}
return parse_tree;
};
return str_format;
})();
// Defining underscore.string
var _s = {
VERSION: '2.4.0',
isBlank: function(str){
return (/^\s*$/).test(makeString(str));
},
stripTags: function(str){
return makeString(str).replace(/<\/?[^>]+>/g, '');
},
capitalize : function(str){
str = makeString(str);
return str.charAt(0).toUpperCase() + str.slice(1);
},
decapitalize : function(str){
str = makeString(str);
return str.charAt(0).toLowerCase() + str.slice(1);
},
chop: function(str, step){
if (str == null) return [];
str = String(str);
step = ~~step;
return step > 0 ? str.match(new RegExp('.{1,' + step + '}', 'g')) : [str];
},
clean: function(str){
return _s.strip(str).replace(/\s+/g, ' ');
},
count: function(str, substr){
str = makeString(str);
substr = makeString(substr);
var count = 0,
pos = 0,
length = substr.length;
while (true) {
pos = str.indexOf(substr, pos);
if (pos === -1) break;
count++;
pos += length;
}
return count;
},
chars: function(str) {
return makeString(str).split('');
},
swapCase: function(str) {
return makeString(str).replace(/\S/g, function(c){
return c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase();
});
},
escapeHTML: function(str) {
return makeString(str).replace(/[&<>"']/g, function(m){ return '&' + reversedEscapeChars[m] + ';'; });
},
unescapeHTML: function(str) {
return makeString(str).replace(/\&([^;]+);/g, function(entity, entityCode){
var match;
if (entityCode in escapeChars) {
return escapeChars[entityCode];
} else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
return String.fromCharCode(parseInt(match[1], 16));
} else if (match = entityCode.match(/^#(\d+)$/)) {
return String.fromCharCode(~~match[1]);
} else {
return entity;
}
});
},
escapeRegExp: function(str){
return makeString(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
},
splice: function(str, i, howmany, substr){
var arr = _s.chars(str);
arr.splice(~~i, ~~howmany, substr);
return arr.join('');
},
insert: function(str, i, substr){
return _s.splice(str, i, 0, substr);
},
include: function(str, needle){
if (needle === '') return true;
return makeString(str).indexOf(needle) !== -1;
},
join: function() {
var args = slice.call(arguments),
separator = args.shift();
return args.join(makeString(separator));
},
lines: function(str) {
if (str == null) return [];
return String(str).split('\n');
},
reverse: function(str){
return _s.chars(str).reverse().join('');
},
startsWith: function(str, starts, position){
str = makeString(str);
starts = '' + starts;
position = position == null ? 0 : Math.min(toPositive(position), str.length);
return str.lastIndexOf(starts) == position;
},
endsWith: function(str, ends, position){
str = makeString(str);
ends = '' + ends;
if (typeof position == 'undefined') {
position = str.length - ends.length;
} else {
position = Math.min(toPositive(position), str.length) - ends.length;
}
return position >= 0 && str.indexOf(ends, position) === position;
},
succ: function(str){
str = makeString(str);
return str.slice(0, -1) + String.fromCharCode(str.charCodeAt(str.length-1) + 1);
},
titleize: function(str){
return makeString(str).toLowerCase().replace(/(?:^|\s|-)\S/g, function(c){ return c.toUpperCase(); });
},
camelize: function(str){
return _s.trim(str).replace(/[-_\s]+(.)?/g, function(match, c){ return c ? c.toUpperCase() : ""; });
},
underscored: function(str){
return _s.trim(str).replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase();
},
dasherize: function(str){
return _s.trim(str).replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase();
},
classify: function(str){
return _s.capitalize(_s.camelize(String(str).replace(/[\W_]/g, ' ')).replace(/\s/g, ''));
},
humanize: function(str){
return _s.capitalize(_s.underscored(str).replace(/_id$/,'').replace(/_/g, ' '));
},
trim: function(str, characters){
str = makeString(str);
if (!characters && nativeTrim) return nativeTrim.call(str);
characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp('^' + characters + '+|' + characters + '+$', 'g'), '');
},
ltrim: function(str, characters){
str = makeString(str);
if (!characters && nativeTrimLeft) return nativeTrimLeft.call(str);
characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp('^' + characters + '+'), '');
},
rtrim: function(str, characters){
str = makeString(str);
if (!characters && nativeTrimRight) return nativeTrimRight.call(str);
characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp(characters + '+$'), '');
},
truncate: function(str, length, truncateStr){
str = makeString(str); truncateStr = truncateStr || '...';
length = ~~length;
return str.length > length ? str.slice(0, length) + truncateStr : str;
},
/**
* _s.prune: a more elegant version of truncate
* prune extra chars, never leaving a half-chopped word.
* @author github.com/rwz
*/
prune: function(str, length, pruneStr){
str = makeString(str); length = ~~length;
pruneStr = pruneStr != null ? String(pruneStr) : '...';
if (str.length <= length) return str;
var tmpl = function(c){ return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' '; },
template = str.slice(0, length+1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
if (template.slice(template.length-2).match(/\w\w/))
template = template.replace(/\s*\S+$/, '');
else
template = _s.rtrim(template.slice(0, template.length-1));
return (template+pruneStr).length > str.length ? str : str.slice(0, template.length)+pruneStr;
},
words: function(str, delimiter) {
if (_s.isBlank(str)) return [];
return _s.trim(str, delimiter).split(delimiter || /\s+/);
},
pad: function(str, length, padStr, type) {
str = makeString(str);
length = ~~length;
var padlen = 0;
if (!padStr)
padStr = ' ';
else if (padStr.length > 1)
padStr = padStr.charAt(0);
switch(type) {
case 'right':
padlen = length - str.length;
return str + strRepeat(padStr, padlen);
case 'both':
padlen = length - str.length;
return strRepeat(padStr, Math.ceil(padlen/2)) + str
+ strRepeat(padStr, Math.floor(padlen/2));
default: // 'left'
padlen = length - str.length;
return strRepeat(padStr, padlen) + str;
}
},
lpad: function(str, length, padStr) {
return _s.pad(str, length, padStr);
},
rpad: function(str, length, padStr) {
return _s.pad(str, length, padStr, 'right');
},
lrpad: function(str, length, padStr) {
return _s.pad(str, length, padStr, 'both');
},
sprintf: sprintf,
vsprintf: function(fmt, argv){
argv.unshift(fmt);
return sprintf.apply(null, argv);
},
toNumber: function(str, decimals) {
if (!str) return 0;
str = _s.trim(str);
if (!str.match(/^-?\d+(?:\.\d+)?$/)) return NaN;
return parseNumber(parseNumber(str).toFixed(~~decimals));
},
numberFormat : function(number, dec, dsep, tsep) {
if (isNaN(number) || number == null) return '';
number = number.toFixed(~~dec);
tsep = typeof tsep == 'string' ? tsep : ',';
var parts = number.split('.'), fnums = parts[0],
decimals = parts[1] ? (dsep || '.') + parts[1] : '';
return fnums.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + tsep) + decimals;
},
strRight: function(str, sep){
str = makeString(str); sep = makeString(sep);
var pos = !sep ? -1 : str.indexOf(sep);
return ~pos ? str.slice(pos+sep.length, str.length) : str;
},
strRightBack: function(str, sep){
str = makeString(str); sep = makeString(sep);
var pos = !sep ? -1 : str.lastIndexOf(sep);
return ~pos ? str.slice(pos+sep.length, str.length) : str;
},
strLeft: function(str, sep){
str = makeString(str); sep = makeString(sep);
var pos = !sep ? -1 : str.indexOf(sep);
return ~pos ? str.slice(0, pos) : str;
},
strLeftBack: function(str, sep){
str = makeString(str); sep = makeString(sep);
var pos = str.lastIndexOf(sep);
return ~pos ? str.slice(0, pos) : str;
},
toSentence: function(array, separator, lastSeparator, serial) {
separator = separator || ', ';
lastSeparator = lastSeparator || ' and ';
var a = array.slice(), lastMember = a.pop();
if (array.length > 2 && serial) lastSeparator = _s.rtrim(separator) + lastSeparator;
return a.length ? a.join(separator) + lastSeparator + lastMember : lastMember;
},
toSentenceSerial: function(array, sep, lastSep) {
return _s.toSentence(array, sep, lastSep, true);
},
slugify: function(str) {
var from = "ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșšŝťțŭùúüűûñÿýçżźž",
to = "aaaaaaaaaccceeeeeghiiiijllnnoooooooossssttuuuuuunyyczzz",
regex = new RegExp(defaultToWhiteSpace(from), 'g');
str = makeString(str).toLowerCase().replace(regex, function(c){
var index = from.indexOf(c);
return to.charAt(index) || '-';
});
return _s.trim(_s.dasherize(str.replace(/[^\w\s-]/g, '-')), '-');
},
surround: function(str, wrapper) {
return [wrapper, str, wrapper].join('');
},
quote: function(str, quoteChar) {
return _s.surround(str, quoteChar || '"');
},
unquote: function(str, quoteChar) {
quoteChar = quoteChar || '"';
if (str[0] === quoteChar && str[str.length-1] === quoteChar)
return str.slice(1,str.length-1);
else return str;
},
exports: function() {
var result = {};
for (var prop in this) {
if (!this.hasOwnProperty(prop) || prop.match(/^(?:include|contains|reverse)$/)) continue;
result[prop] = this[prop];
}
return result;
},
repeat: function(str, qty, separator){
str = makeString(str);
qty = ~~qty;
// using faster implementation if separator is not needed;
if (separator == null) return strRepeat(str, qty);
// this one is about 300x slower in Google Chrome
for (var repeat = []; qty > 0; repeat[--qty] = str) {}
return repeat.join(separator);
},
naturalCmp: function(str1, str2){
if (str1 == str2) return 0;
if (!str1) return -1;
if (!str2) return 1;
var cmpRegex = /(\.\d+)|(\d+)|(\D+)/g,
tokens1 = String(str1).match(cmpRegex),
tokens2 = String(str2).match(cmpRegex),
count = Math.min(tokens1.length, tokens2.length);
for(var i = 0; i < count; i++) {
var a = tokens1[i], b = tokens2[i];
if (a !== b){
var num1 = +a;
var num2 = +b;
if (num1 === num1 && num2 === num2){
return num1 > num2 ? 1 : -1;
}
return a < b ? -1 : 1;
}
}
if (tokens1.length != tokens2.length)
return tokens1.length - tokens2.length;
return str1 < str2 ? -1 : 1;
},
levenshtein: function(str1, str2) {
str1 = makeString(str1); str2 = makeString(str2);
var current = [], prev, value;
for (var i = 0; i <= str2.length; i++)
for (var j = 0; j <= str1.length; j++) {
if (i && j)
if (str1.charAt(j - 1) === str2.charAt(i - 1))
value = prev;
else
value = Math.min(current[j], current[j - 1], prev) + 1;
else
value = i + j;
prev = current[j];
current[j] = value;
}
return current.pop();
},
toBoolean: function(str, trueValues, falseValues) {
if (typeof str === "number") str = "" + str;
if (typeof str !== "string") return !!str;
str = _s.trim(str);
if (boolMatch(str, trueValues || ["true", "1"])) return true;
if (boolMatch(str, falseValues || ["false", "0"])) return false;
}
};
// 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;
_s.toBool = _s.toBoolean;
// Exporting
// CommonJS module is defined
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports)
module.exports = _s;
exports._s = _s;
}
// Register as a named module with AMD.
if (typeof define === 'function' && define.amd)
define('underscore.string', [], function(){ return _s; });
// Integrate with Underscore.js if defined
// or create our own underscore object.
root._ = root._ || {};
root._.string = root._.str = _s;
}(this, String);

@ -0,0 +1,4 @@
module.exports = function lines(str) {
if (str == null) return [];
return String(str).split('\n');
};

@ -0,0 +1,5 @@
var pad = require('./pad');
module.exports = function lpad(str, length, padStr) {
return pad(str, length, padStr);
};

@ -0,0 +1,5 @@
var pad = require('./pad');
module.exports = function lrpad(str, length, padStr) {
return pad(str, length, padStr, 'both');
};

@ -0,0 +1,10 @@
var makeString = require('./helper/makeString');
var defaultToWhiteSpace = require('./helper/defaultToWhiteSpace');
var nativeTrimLeft = String.prototype.trimLeft;
module.exports = function ltrim(str, characters) {
str = makeString(str);
if (!characters && nativeTrimLeft) return nativeTrimLeft.call(str);
characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp('^' + characters + '+'), '');
};

@ -0,0 +1,29 @@
module.exports = function naturalCmp(str1, str2) {
if (str1 == str2) return 0;
if (!str1) return -1;
if (!str2) return 1;
var cmpRegex = /(\.\d+)|(\d+)|(\D+)/g,
tokens1 = String(str1).match(cmpRegex),
tokens2 = String(str2).match(cmpRegex),
count = Math.min(tokens1.length, tokens2.length);
for (var i = 0; i < count; i++) {
var a = tokens1[i],
b = tokens2[i];
if (a !== b) {
var num1 = +a;
var num2 = +b;
if (num1 === num1 && num2 === num2) {
return num1 > num2 ? 1 : -1;
}
return a < b ? -1 : 1;
}
}
if (tokens1.length != tokens2.length)
return tokens1.length - tokens2.length;
return str1 < str2 ? -1 : 1;
};

@ -0,0 +1,12 @@
module.exports = function numberFormat(number, dec, dsep, tsep) {
if (isNaN(number) || number == null) return '';
number = number.toFixed(~~dec);
tsep = typeof tsep == 'string' ? tsep : ',';
var parts = number.split('.'),
fnums = parts[0],
decimals = parts[1] ? (dsep || '.') + parts[1] : '';
return fnums.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + tsep) + decimals;
};

@ -17,9 +17,9 @@
"underscore",
"string"
],
"main": "./lib/underscore.string.js",
"main": "./underscore.string.js",
"directories": {
"lib": "./lib"
"lib": "./"
},
"engines": {
"node": "*"
@ -45,8 +45,9 @@
"gulp-qunit": "~1.0.0",
"gulp-rename": "~1.2.0",
"gulp-uglify": "~1.0.1",
"gulp-param": "~0.6.1",
"gulp-param": "~0.6.3",
"gulp-bump": "~0.1.11",
"gulp-replace": "~0.5.0"
"gulp-replace": "~0.5.0",
"gulp-browserify": "~0.5.0"
}
}

@ -0,0 +1,26 @@
var makeString = require('./helper/makeString');
var strRepeat = require('./helper/strRepeat');
module.exports = function pad(str, length, padStr, type) {
str = makeString(str);
length = ~~length;
var padlen = 0;
if (!padStr)
padStr = ' ';
else if (padStr.length > 1)
padStr = padStr.charAt(0);
switch (type) {
case 'right':
padlen = length - str.length;
return str + strRepeat(padStr, padlen);
case 'both':
padlen = length - str.length;
return strRepeat(padStr, Math.ceil(padlen / 2)) + str + strRepeat(padStr, Math.floor(padlen / 2));
default: // 'left'
padlen = length - str.length;
return strRepeat(padStr, padlen) + str;
}
};

@ -0,0 +1,27 @@
/**
* _s.prune: a more elegant version of truncate
* prune extra chars, never leaving a half-chopped word.
* @author github.com/rwz
*/
var makeString = require('./helper/makeString');
var rtrim = require('./rtrim');
module.exports = function prune(str, length, pruneStr) {
str = makeString(str);
length = ~~length;
pruneStr = pruneStr != null ? String(pruneStr) : '...';
if (str.length <= length) return str;
var tmpl = function(c) {
return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' ';
},
template = str.slice(0, length + 1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
if (template.slice(template.length - 2).match(/\w\w/))
template = template.replace(/\s*\S+$/, '');
else
template = rtrim(template.slice(0, template.length - 1));
return (template + pruneStr).length > str.length ? str : str.slice(0, template.length) + pruneStr;
};

@ -0,0 +1,5 @@
var surround = require('./surround');
module.exports = function quote(str, quoteChar) {
return surround(str, quoteChar || '"');
};

@ -0,0 +1,15 @@
var makeString = require('./helper/makeString');
var strRepeat = require('./helper/strRepeat');
module.exports = function repeat(str, qty, separator) {
str = makeString(str);
qty = ~~qty;
// using faster implementation if separator is not needed;
if (separator == null) return strRepeat(str, qty);
// this one is about 300x slower in Google Chrome
for (var repeat = []; qty > 0; repeat[--qty] = str) {}
return repeat.join(separator);
};

@ -0,0 +1,5 @@
var chars = require('./chars');
module.exports = function reverse(str) {
return chars(str).reverse().join('');
};

@ -0,0 +1,5 @@
var pad = require('./pad');
module.exports = function rpad(str, length, padStr) {
return pad(str, length, padStr, 'right');
};

@ -0,0 +1,10 @@
var makeString = require('./helper/makeString');
var defaultToWhiteSpace = require('./helper/defaultToWhiteSpace');
var nativeTrimRight = String.prototype.trimRight;
module.exports = function rtrim(str, characters) {
str = makeString(str);
if (!characters && nativeTrimRight) return nativeTrimRight.call(str);
characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp(characters + '+$'), '');
};

@ -0,0 +1,17 @@
var makeString = require('./helper/makeString');
var defaultToWhiteSpace = require('./helper/defaultToWhiteSpace');
var trim = require('./trim');
var dasherize = require('./dasherize');
module.exports = function slugify(str) {
var from = "ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșšŝťțŭùúüűûñÿýçżźž",
to = "aaaaaaaaaccceeeeeghiiiijllnnoooooooossssttuuuuuunyyczzz",
regex = new RegExp(defaultToWhiteSpace(from), 'g');
str = makeString(str).toLowerCase().replace(regex, function(c){
var index = from.indexOf(c);
return to.charAt(index) || '-';
});
return trim(dasherize(str.replace(/[^\w\s-]/g, '-')), '-');
};

@ -0,0 +1,7 @@
var chars = require('./chars');
module.exports = function splice(str, i, howmany, substr) {
var arr = chars(str);
arr.splice(~~i, ~~howmany, substr);
return arr.join('');
};

@ -0,0 +1,124 @@
// sprintf() for JavaScript 0.7-beta1
// http://www.diveintojavascript.com/projects/javascript-sprintf
//
// Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
// All rights reserved.
var strRepeat = require('./helper/strRepeat');
var toString = Object.prototype.toString;
var sprintf = (function() {
function get_type(variable) {
return toString.call(variable).slice(8, -1).toLowerCase();
}
var str_repeat = strRepeat;
var str_format = function() {
if (!str_format.cache.hasOwnProperty(arguments[0])) {
str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
}
return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
};
str_format.format = function(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
for (i = 0; i < tree_length; i++) {
node_type = get_type(parse_tree[i]);
if (node_type === 'string') {
output.push(parse_tree[i]);
}
else if (node_type === 'array') {
match = parse_tree[i]; // convenience purposes only
if (match[2]) { // keyword argument
arg = argv[cursor];
for (k = 0; k < match[2].length; k++) {
if (!arg.hasOwnProperty(match[2][k])) {
throw new Error(sprintf('[_.sprintf] property "%s" does not exist', match[2][k]));
}
arg = arg[match[2][k]];
}
} else if (match[1]) { // positional argument (explicit)
arg = argv[match[1]];
}
else { // positional argument (implicit)
arg = argv[cursor++];
}
if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
throw new Error(sprintf('[_.sprintf] expecting number but found %s', get_type(arg)));
}
switch (match[8]) {
case 'b': arg = arg.toString(2); break;
case 'c': arg = String.fromCharCode(arg); break;
case 'd': arg = parseInt(arg, 10); break;
case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
case 'o': arg = arg.toString(8); break;
case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
case 'u': arg = Math.abs(arg); break;
case 'x': arg = arg.toString(16); break;
case 'X': arg = arg.toString(16).toUpperCase(); break;
}
arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
pad_length = match[6] - String(arg).length;
pad = match[6] ? str_repeat(pad_character, pad_length) : '';
output.push(match[5] ? arg + pad : pad + arg);
}
}
return output.join('');
};
str_format.cache = {};
str_format.parse = function(fmt) {
var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
while (_fmt) {
if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
}
else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
parse_tree.push('%');
}
else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
var field_list = [], replacement_field = match[2], field_match = [];
if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else {
throw new Error('[_.sprintf] huh?');
}
}
}
else {
throw new Error('[_.sprintf] huh?');
}
match[2] = field_list;
}
else {
arg_names |= 2;
}
if (arg_names === 3) {
throw new Error('[_.sprintf] mixing positional and named placeholders is not (yet) supported');
}
parse_tree.push(match);
}
else {
throw new Error('[_.sprintf] huh?');
}
_fmt = _fmt.substring(match[0].length);
}
return parse_tree;
};
return str_format;
})();
module.exports = sprintf;

@ -0,0 +1,9 @@
var makeString = require('./helper/makeString');
var toPositive = require('./helper/toPositive');
module.exports = function startsWith(str, starts, position) {
str = makeString(str);
starts = '' + starts;
position = position == null ? 0 : Math.min(toPositive(position), str.length);
return str.lastIndexOf(starts) == position;
};

@ -0,0 +1,8 @@
var makeString = require('./helper/makeString');
module.exports = function strLeft(str, sep) {
str = makeString(str);
sep = makeString(sep);
var pos = !sep ? -1 : str.indexOf(sep);
return~ pos ? str.slice(0, pos) : str;
};

@ -0,0 +1,8 @@
var makeString = require('./helper/makeString');
module.exports = function strLeftBack(str, sep) {
str = makeString(str);
sep = makeString(sep);
var pos = str.lastIndexOf(sep);
return~ pos ? str.slice(0, pos) : str;
};

@ -0,0 +1,8 @@
var makeString = require('./helper/makeString');
module.exports = function strRight(str, sep) {
str = makeString(str);
sep = makeString(sep);
var pos = !sep ? -1 : str.indexOf(sep);
return~ pos ? str.slice(pos + sep.length, str.length) : str;
};

@ -0,0 +1,8 @@
var makeString = require('./helper/makeString');
module.exports = function strRightBack(str, sep) {
str = makeString(str);
sep = makeString(sep);
var pos = !sep ? -1 : str.lastIndexOf(sep);
return~ pos ? str.slice(pos + sep.length, str.length) : str;
};

@ -0,0 +1,5 @@
var makeString = require('./helper/makeString');
module.exports = function stripTags(str) {
return makeString(str).replace(/<\/?[^>]+>/g, '');
};

@ -0,0 +1,6 @@
var makeString = require('./helper/makeString');
module.exports = function succ(str) {
str = makeString(str);
return str.slice(0, -1) + String.fromCharCode(str.charCodeAt(str.length - 1) + 1);
};

@ -0,0 +1,3 @@
module.exports = function surround(str, wrapper) {
return [wrapper, str, wrapper].join('');
};

@ -0,0 +1,7 @@
var makeString = require('./helper/makeString');
module.exports = function swapCase(str) {
return makeString(str).replace(/\S/g, function(c) {
return c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase();
});
};

@ -8,12 +8,17 @@
<script type="text/javascript" src="test_underscore/vendor/qunit.js"></script>
<script type="text/javascript" src="test_underscore/vendor/jslitmus.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="../lib/underscore.string.js"></script>
<script type="text/javascript" src="../underscore.string.compiled.js"></script>
<script type="text/javascript" src="strings.js"></script>
<script type="text/javascript" src="speed.js"></script>
</head>
<body>
<h1 id="qunit-header">Underscore.string Test Suite</h1>
<h1 id="qunit-header">
Underscore.string Test Suite
<span style="color:#fefefe; font-size:0.5em; color:#ef3d47;">
Make sure to run gulp browserify first!
</span>
</h1>
<h2 id="qunit-banner"></h2>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>

@ -5,12 +5,17 @@
<link rel="stylesheet" href="test_underscore/vendor/qunit.css" type="text/css" media="screen" />
<script type="text/javascript" src="test_underscore/vendor/jquery.js"></script>
<script type="text/javascript" src="test_underscore/vendor/qunit.js"></script>
<script type="text/javascript" src="../lib/underscore.string.js"></script>
<script type="text/javascript" src="../underscore.string.compiled.js"></script>
<script type="text/javascript" src="strings_standalone.js"></script>
</head>
<body>
<h1 id="qunit-header">Underscore.string Test Suite</h1>
<h1 id="qunit-header">
Underscore.string Test Suite
<span style="color:#fefefe; font-size:0.5em; color:#ef3d47;">
Make sure to run gulp browserify first!
</span>
</h1>
<h2 id="qunit-banner"></h2>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>

@ -7,7 +7,7 @@
<script src="vendor/qunit.js"></script>
<script src="vendor/jslitmus.js"></script>
<script src="../underscore.js"></script>
<script src="../../lib/underscore.string.js"></script>
<script src="../../underscore.string.compiled.js"></script>
<script src="collections.js"></script>
<script src="arrays.js"></script>

@ -0,0 +1,7 @@
var makeString = require('./helper/makeString');
module.exports = function titleize(str) {
return makeString(str).toLowerCase().replace(/(?:^|\s|-)\S/g, function(c) {
return c.toUpperCase();
});
};

@ -0,0 +1,20 @@
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;
if (matcher.test && matcher.test(s)) return true;
if (matcher.toLowerCase() === down) return true;
}
}
module.exports = function toBoolean(str, trueValues, falseValues) {
if (typeof str === "number") str = "" + str;
if (typeof str !== "string") return !!str;
str = trim(str);
if (boolMatch(str, trueValues || ["true", "1"])) return true;
if (boolMatch(str, falseValues || ["false", "0"])) return false;
};

@ -0,0 +1,11 @@
var trim = require('./trim');
var parseNumber = function(source) {
return source * 1 || 0;
};
module.exports = function toNumber(str, decimals) {
if (!str) return 0;
str = trim(str);
if (!str.match(/^-?\d+(?:\.\d+)?$/)) return NaN;
return parseNumber(parseNumber(str).toFixed(~~decimals));
};

@ -0,0 +1,12 @@
var rtrim = require('./rtrim');
module.exports = function toSentence(array, separator, lastSeparator, serial) {
separator = separator || ', ';
lastSeparator = lastSeparator || ' and ';
var a = array.slice(),
lastMember = a.pop();
if (array.length > 2 && serial) lastSeparator = rtrim(separator) + lastSeparator;
return a.length ? a.join(separator) + lastSeparator + lastMember : lastMember;
};

@ -0,0 +1,5 @@
var toSentence = require('./toSentence');
module.exports = function toSentenceSerial(array, sep, lastSep) {
return toSentence(array, sep, lastSep, true);
};

@ -0,0 +1,10 @@
var makeString = require('./helper/makeString');
var defaultToWhiteSpace = require('./helper/defaultToWhiteSpace');
var nativeTrim = String.prototype.trim;
module.exports = function trim(str, characters) {
str = makeString(str);
if (!characters && nativeTrim) return nativeTrim.call(str);
characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp('^' + characters + '+|' + characters + '+$', 'g'), '');
};

@ -0,0 +1,8 @@
var makeString = require('./helper/makeString');
module.exports = function truncate(str, length, truncateStr) {
str = makeString(str);
truncateStr = truncateStr || '...';
length = ~~length;
return str.length > length ? str.slice(0, length) + truncateStr : str;
};

@ -0,0 +1,93 @@
// Underscore.string
// (c) 2010 Esa-Matti Suuronen <esa-matti aet suuronen dot org>
// Underscore.string is freely distributable under the terms of the MIT license.
// Documentation: https://github.com/epeli/underscore.string
// Some code is borrowed from MooTools and Alexandru Marasteanu.
// Version '2.4.0'
'use strict';
// Defining underscore.string
var _s = {
VERSION: '2.4.0'
};
_s.isBlank = require('./isBlank');
_s.stripTags = require('./stripTags');
_s.capitalize = require('./capitalize');
_s.decapitalize = require('./decapitalize');
_s.chop = require('./chop');
_s.trim = require('./trim');
_s.clean = require('./clean');
_s.count = require('./count');
_s.chars = require('./chars');
_s.swapCase = require('./swapCase');
_s.escapeHTML = require('./escapeHTML');
_s.unescapeHTML = require('./unescapeHTML');
_s.splice = require('./splice');
_s.insert = require('./insert');
_s.include = require('./include');
_s.join = require('./join');
_s.lines = require('./lines');
_s.reverse = require('./reverse');
_s.startsWith = require('./startsWith');
_s.endsWith = require('./endsWith');
_s.succ = require('./succ');
_s.titleize = require('./titleize');
_s.camelize = require('./camelize');
_s.underscored = require('./underscored');
_s.dasherize = require('./dasherize');
_s.classify = require('./classify');
_s.humanize = require('./humanize');
_s.ltrim = require('./ltrim');
_s.rtrim = require('./rtrim');
_s.truncate = require('./truncate');
_s.prune = require('./prune');
_s.words = require('./words');
_s.pad = require('./pad');
_s.lpad = require('./lpad');
_s.rpad = require('./rpad');
_s.lrpad = require('./lrpad');
_s.sprintf = require('./sprintf');
_s.vsprintf = require('./vsprintf');
_s.toNumber = require('./toNumber');
_s.numberFormat = require('./numberFormat');
_s.strRight = require('./strRight');
_s.strRightBack = require('./strRightBack');
_s.strLeft = require('./strLeft');
_s.strLeftBack = require('./strLeftBack');
_s.toSentence = require('./toSentence');
_s.toSentenceSerial = require('./toSentenceSerial');
_s.slugify = require('./slugify');
_s.surround = require('./surround');
_s.quote = require('./quote');
_s.unquote = require('./unquote');
_s.repeat = require('./repeat');
_s.naturalCmp = require('./naturalCmp');
_s.levenshtein = require('./levenshtein');
_s.toBoolean = require('./toBoolean');
_s.exports = require('./exports');
_s.escapeRegExp = require('./helper/escapeRegExp');
// 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;
_s.toBool = _s.toBoolean;
// Exporting
// Integrate with Underscore.js if defined
// or create our own underscore object.
global._ = global._ || {};
global._.string = global._.str = _s;
this._ = this._ || {};
this._.string = this._.str = _s;
// CommonJS module is defined
module.exports = _s;
exports._s = _s;

@ -0,0 +1,5 @@
var trim = require('./trim');
module.exports = function underscored(str) {
return trim(str).replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase();
};

@ -0,0 +1,18 @@
var makeString = require('./helper/makeString');
var escapeChars = require('./helper/escapeChars');
module.exports = function unescapeHTML(str) {
return makeString(str).replace(/\&([^;]+);/g, function(entity, entityCode) {
var match;
if (entityCode in escapeChars) {
return escapeChars[entityCode];
} else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
return String.fromCharCode(parseInt(match[1], 16));
} else if (match = entityCode.match(/^#(\d+)$/)) {
return String.fromCharCode(~~match[1]);
} else {
return entity;
}
});
};

@ -0,0 +1,6 @@
module.exports = function unquote(str, quoteChar) {
quoteChar = quoteChar || '"';
if (str[0] === quoteChar && str[str.length - 1] === quoteChar)
return str.slice(1, str.length - 1);
else return str;
};

@ -0,0 +1,6 @@
var sprintf = require('./sprintf');
module.exports = function vsprintf(fmt, argv) {
argv.unshift(fmt);
return sprintf.apply(null, argv);
};

@ -0,0 +1,7 @@
var isBlank = require('./isBlank');
var trim = require('./trim');
module.exports = function words(str, delimiter) {
if (isBlank(str)) return [];
return trim(str, delimiter).split(delimiter || /\s+/);
};
Loading…
Cancel
Save