underscore.string
Advanced tools
Comparing version 2.0.0 to 2.1.0
@@ -1,14 +0,1 @@ | ||
(function(k){var o=String.prototype.trim,l=function(a,b){for(var c=[];b>0;c[--b]=a);return c.join("")},d=function(a){return function(){for(var b=Array.prototype.slice.call(arguments),c=0;c<b.length;c++)b[c]=b[c]==null?"":""+b[c];return a.apply(null,b)}},m=function(){function a(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}var b=function(){b.cache.hasOwnProperty(arguments[0])||(b.cache[arguments[0]]=b.parse(arguments[0]));return b.format.call(null,b.cache[arguments[0]],arguments)}; | ||
b.format=function(b,n){var e=1,d=b.length,f="",j=[],h,i,g,k;for(h=0;h<d;h++)if(f=a(b[h]),f==="string")j.push(b[h]);else if(f==="array"){g=b[h];if(g[2]){f=n[e];for(i=0;i<g[2].length;i++){if(!f.hasOwnProperty(g[2][i]))throw m('[_.sprintf] property "%s" does not exist',g[2][i]);f=f[g[2][i]]}}else f=g[1]?n[g[1]]:n[e++];if(/[^s]/.test(g[8])&&a(f)!="number")throw m("[_.sprintf] expecting number but found %s",a(f));switch(g[8]){case "b":f=f.toString(2);break;case "c":f=String.fromCharCode(f);break;case "d":f= | ||
parseInt(f,10);break;case "e":f=g[7]?f.toExponential(g[7]):f.toExponential();break;case "f":f=g[7]?parseFloat(f).toFixed(g[7]):parseFloat(f);break;case "o":f=f.toString(8);break;case "s":f=(f=String(f))&&g[7]?f.substring(0,g[7]):f;break;case "u":f=Math.abs(f);break;case "x":f=f.toString(16);break;case "X":f=f.toString(16).toUpperCase()}f=/[def]/.test(g[8])&&g[3]&&f>=0?"+"+f:f;i=g[4]?g[4]=="0"?"0":g[4].charAt(1):" ";k=g[6]-String(f).length;i=g[6]?l(i,k):"";j.push(g[5]?f+i:i+f)}return j.join("")};b.cache= | ||
{};b.parse=function(a){for(var b=[],e=[],d=0;a;){if((b=/^[^\x25]+/.exec(a))!==null)e.push(b[0]);else if((b=/^\x25{2}/.exec(a))!==null)e.push("%");else if((b=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(a))!==null){if(b[2]){d|=1;var f=[],j=b[2],h=[];if((h=/^([a-z_][a-z_\d]*)/i.exec(j))!==null)for(f.push(h[1]);(j=j.substring(h[0].length))!=="";)if((h=/^\.([a-z_][a-z_\d]*)/i.exec(j))!==null)f.push(h[1]);else if((h=/^\[(\d+)\]/.exec(j))!==null)f.push(h[1]); | ||
else throw"[_.sprintf] huh?";else throw"[_.sprintf] huh?";b[2]=f}else d|=2;if(d===3)throw"[_.sprintf] mixing positional and named placeholders is not (yet) supported";e.push(b)}else throw"[_.sprintf] huh?";a=a.substring(b[0].length)}return e};return b}(),e={VERSION:"1.2.0",isBlank:d(function(a){return/^\s*$/.test(a)}),stripTags:d(function(a){return a.replace(/<\/?[^>]+>/ig,"")}),capitalize:d(function(a){return a.charAt(0).toUpperCase()+a.substring(1).toLowerCase()}),chop:d(function(a,b){for(var b= | ||
b*1||0||a.length,c=[],e=0;e<a.length;)c.push(a.slice(e,e+b)),e+=b;return c}),clean:d(function(a){return e.strip(a.replace(/\s+/g," "))}),count:d(function(a,b){for(var c=0,e,d=0;d<a.length;)e=a.indexOf(b,d),e>=0&&c++,d=d+(e>=0?e:0)+b.length;return c}),chars:d(function(a){return a.split("")}),escapeHTML:d(function(a){return a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}),unescapeHTML:d(function(a){return a.replace(/</g,"<").replace(/>/g, | ||
">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")}),escapeRegExp:d(function(a){return a.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1")}),insert:d(function(a,b,c){a=a.split("");a.splice(b*1||0,0,c);return a.join("")}),include:d(function(a,b){return a.indexOf(b)!==-1}),join:d(function(a){var b=Array.prototype.slice.call(arguments);return b.join(b.shift())}),lines:d(function(a){return a.split("\n")}),reverse:d(function(a){return Array.prototype.reverse.apply(String(a).split("")).join("")}), | ||
splice:d(function(a,b,c,e){a=a.split("");a.splice(b*1||0,c*1||0,e);return a.join("")}),startsWith:d(function(a,b){return a.length>=b.length&&a.substring(0,b.length)===b}),endsWith:d(function(a,b){return a.length>=b.length&&a.substring(a.length-b.length)===b}),succ:d(function(a){var b=a.split("");b.splice(a.length-1,1,String.fromCharCode(a.charCodeAt(a.length-1)+1));return b.join("")}),titleize:d(function(a){for(var a=a.split(" "),b,c=0;c<a.length;c++)b=a[c].split(""),typeof b[0]!=="undefined"&&(b[0]= | ||
b[0].toUpperCase()),c+1===a.length?a[c]=b.join(""):a[c]=b.join("")+" ";return a.join("")}),camelize:d(function(a){return e.trim(a).replace(/(\-|_|\s)+(.)?/g,function(a,c,e){return e?e.toUpperCase():""})}),underscored:function(a){return e.trim(a).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/\-|\s+/g,"_").toLowerCase()},dasherize:function(a){return e.trim(a).replace(/([a-z\d])([A-Z]+)/g,"$1-$2").replace(/^([A-Z]+)/,"-$1").replace(/\_|\s+/g,"-").toLowerCase()},humanize:function(a){return e.capitalize(this.underscored(a).replace(/_id$/, | ||
"").replace(/_/g," "))},trim:d(function(a,b){if(!b&&o)return o.call(a);b=b?e.escapeRegExp(b):"\\s";return a.replace(RegExp("^["+b+"]+|["+b+"]+$","g"),"")}),ltrim:d(function(a,b){b=b?e.escapeRegExp(b):"\\s";return a.replace(RegExp("^["+b+"]+","g"),"")}),rtrim:d(function(a,b){b=b?e.escapeRegExp(b):"\\s";return a.replace(RegExp("["+b+"]+$","g"),"")}),truncate:d(function(a,b,c){b=b*1||0;return a.length>b?a.slice(0,b)+(c||"..."):a}),prune:d(function(a,b,c){var c=c||"...",b=b*1||0,d="",d=a.substring(b- | ||
1,b+1).search(/^\w\w$/)===0?e.rtrim(a.slice(0,b).replace(/([\W][\w]*)$/,"")):e.rtrim(a.slice(0,b)),d=d.replace(/\W+$/,"");return d.length+c.length>a.length?a:d+c}),words:function(a,b){return String(a).split(b||" ")},pad:d(function(a,b,c,e){var d="",d=0,b=b*1||0;c?c.length>1&&(c=c.charAt(0)):c=" ";switch(e){case "right":d=b-a.length;d=l(c,d);a+=d;break;case "both":d=b-a.length;d={left:l(c,Math.ceil(d/2)),right:l(c,Math.floor(d/2))};a=d.left+a+d.right;break;default:d=b-a.length,d=l(c,d),a=d+a}return a}), | ||
lpad:function(a,b,c){return e.pad(a,b,c)},rpad:function(a,b,c){return e.pad(a,b,c,"right")},lrpad:function(a,b,c){return e.pad(a,b,c,"both")},sprintf:m,vsprintf:function(a,b){b.unshift(a);return m.apply(null,b)},toNumber:function(a,b){var c;c=(a*1||0).toFixed(b*1||0)*1||0;return!(c===0&&a!=="0"&&a!==0)?c:Number.NaN},strRight:d(function(a,b){var c=!b?-1:a.indexOf(b);return c!=-1?a.slice(c+b.length,a.length):a}),strRightBack:d(function(a,b){var c=!b?-1:a.lastIndexOf(b);return c!=-1?a.slice(c+b.length, | ||
a.length):a}),strLeft:d(function(a,b){var c=!b?-1:a.indexOf(b);return c!=-1?a.slice(0,c):a}),strLeftBack:d(function(a,b){var c=a.lastIndexOf(b);return c!=-1?a.slice(0,c):a}),exports:function(){var a={},b;for(b in this)if(this.hasOwnProperty(b)&&!(b=="include"||b=="contains"||b=="reverse"))a[b]=this[b];return a}};e.strip=e.trim;e.lstrip=e.ltrim;e.rstrip=e.rtrim;e.center=e.lrpad;e.ljust=e.lpad;e.rjust=e.rpad;e.contains=e.include;if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)module.exports= | ||
e;exports._s=e}else typeof k._!=="undefined"?(k._.string=e,k._.str=k._.string):k._={string:e,str:e}})(this||window); | ||
(function(a){"use strict";var b=String.prototype.trim,c=String.prototype.trimRight,d=String.prototype.trimLeft,e=function(a){return a*1||0},f=function(a,b,c){a+="",b=~~b;for(var d=[];b>0;d[--b]=a);return d.join(c==null?"":c)},g=function(a){return Array.prototype.slice.call(a)},h=function(a){return a!=null?"["+j.escapeRegExp(""+a)+"]":"\\s"},i=function(){function a(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}var b=f,c=function(){return c.cache.hasOwnProperty(arguments[0])||(c.cache[arguments[0]]=c.parse(arguments[0])),c.format.call(null,c.cache[arguments[0]],arguments)};return c.format=function(c,d){var e=1,f=c.length,g="",h,j=[],k,l,m,n,o,p;for(k=0;k<f;k++){g=a(c[k]);if(g==="string")j.push(c[k]);else if(g==="array"){m=c[k];if(m[2]){h=d[e];for(l=0;l<m[2].length;l++){if(!h.hasOwnProperty(m[2][l]))throw new Error(i('[_.sprintf] property "%s" does not exist',m[2][l]));h=h[m[2][l]]}}else m[1]?h=d[m[1]]:h=d[e++];if(/[^s]/.test(m[8])&&a(h)!="number")throw new Error(i("[_.sprintf] expecting number but found %s",a(h)));switch(m[8]){case"b":h=h.toString(2);break;case"c":h=String.fromCharCode(h);break;case"d":h=parseInt(h,10);break;case"e":h=m[7]?h.toExponential(m[7]):h.toExponential();break;case"f":h=m[7]?parseFloat(h).toFixed(m[7]):parseFloat(h);break;case"o":h=h.toString(8);break;case"s":h=(h=String(h))&&m[7]?h.substring(0,m[7]):h;break;case"u":h=Math.abs(h);break;case"x":h=h.toString(16);break;case"X":h=h.toString(16).toUpperCase()}h=/[def]/.test(m[8])&&m[3]&&h>=0?"+"+h:h,o=m[4]?m[4]=="0"?"0":m[4].charAt(1):" ",p=m[6]-String(h).length,n=m[6]?b(o,p):"",j.push(m[5]?h+n:n+h)}}return j.join("")},c.cache={},c.parse=function(a){var b=a,c=[],d=[],e=0;while(b){if((c=/^[^\x25]+/.exec(b))!==null)d.push(c[0]);else if((c=/^\x25{2}/.exec(b))!==null)d.push("%");else{if((c=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(b))===null)throw new Error("[_.sprintf] huh?");if(c[2]){e|=1;var f=[],g=c[2],h=[];if((h=/^([a-z_][a-z_\d]*)/i.exec(g))===null)throw new Error("[_.sprintf] huh?");f.push(h[1]);while((g=g.substring(h[0].length))!=="")if((h=/^\.([a-z_][a-z_\d]*)/i.exec(g))!==null)f.push(h[1]);else{if((h=/^\[(\d+)\]/.exec(g))===null)throw new Error("[_.sprintf] huh?");f.push(h[1])}c[2]=f}else e|=2;if(e===3)throw new Error("[_.sprintf] mixing positional and named placeholders is not (yet) supported");d.push(c)}b=b.substring(c[0].length)}return d},c}(),j={VERSION:"2.0.0",isBlank:function(a){return/^\s*$/.test(a)},stripTags:function(a){return(""+a).replace(/<\/?[^>]+>/ig,"")},capitalize:function(a){return a+="",a.charAt(0).toUpperCase()+a.substring(1).toLowerCase()},chop:function(a,b){a+="",b=~~b||a.length;var c=[];for(var d=0;d<a.length;)c.push(a.slice(d,d+b)),d+=b;return c},clean:function(a){return j.strip((""+a).replace(/\s+/g," "))},count:function(a,b){return a+="",b+="",a.split(b).length-1},chars:function(a){return(""+a).split("")},escapeHTML:function(a){return(""+a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")},unescapeHTML:function(a){return(""+a).replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")},escapeRegExp:function(a){return a.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1")},insert:function(a,b,c){var d=(""+a).split("");return d.splice(~~b,0,""+c),d.join("")},include:function(a,b){return(""+a).indexOf(b)!==-1},join:function(a){var b=g(arguments);return b.join(b.shift())},lines:function(a){return(""+a).split("\n")},reverse:function(a){return Array.prototype.reverse.apply(String(a).split("")).join("")},splice:function(a,b,c,d){var e=(""+a).split("");return e.splice(~~b,~~c,d),e.join("")},startsWith:function(a,b){return a+="",b+="",a.length>=b.length&&a.substring(0,b.length)===b},endsWith:function(a,b){return a+="",b+="",a.length>=b.length&&a.substring(a.length-b.length)===b},succ:function(a){a+="";var b=a.split("");return b.splice(a.length-1,1,String.fromCharCode(a.charCodeAt(a.length-1)+1)),b.join("")},titleize:function(a){return(""+a).replace(/\b./g,function(a){return a.toUpperCase()})},camelize:function(a){return j.trim(a).replace(/(\-|_|\s)+(.)?/g,function(a,b,c){return c?c.toUpperCase():""})},underscored:function(a){return j.trim(a).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()},dasherize:function(a){return j.trim(a).replace(/[_\s]+/g,"-").replace(/([A-Z])/g,"-$1").replace(/-+/g,"-").toLowerCase()},humanize:function(a){return j.capitalize(this.underscored(a).replace(/_id$/,"").replace(/_/g," "))},trim:function(a,c){return a+="",!c&&b?b.call(a):(c=h(c),a.replace(new RegExp("^"+c+"+|"+c+"+$","g"),""))},ltrim:function(a,b){return!b&&d?d.call(a):(b=h(b),(""+a).replace(new RegExp("^"+b+"+","g"),""))},rtrim:function(a,b){return!b&&c?c.call(a):(b=h(b),(""+a).replace(new RegExp(b+"+$","g"),""))},truncate:function(a,b,c){return a+="",c=c||"...",b=~~b,a.length>b?a.slice(0,b)+c:a},prune:function(a,b,c){a+="",b=~~b,c=c!=null?""+c:"...";var d,e,f=a.replace(/\W/g,function(a){return a.toUpperCase()!==a.toLowerCase()?"A":" "});return e=f.substring(b,b+1),d=f.slice(0,b),e&&e.match(/\S/)&&(d=d.replace(/\s\S+$/,"")),d=j.rtrim(d),(d+c).length>a.length?a:a.substring(0,d.length)+c},words:function(a,b){return _.trim(a,b).split(b||/\s+/)},pad:function(a,b,c,d){a+="";var e="",g=0;b=~~b,c?c.length>1&&(c=c.charAt(0)):c=" ";switch(d){case"right":g=b-a.length,e=f(c,g),a+=e;break;case"both":g=b-a.length,e={left:f(c,Math.ceil(g/2)),right:f(c,Math.floor(g/2))},a=e.left+a+e.right;break;default:g=b-a.length,e=f(c,g),a=e+a}return a},lpad:function(a,b,c){return j.pad(a,b,c)},rpad:function(a,b,c){return j.pad(a,b,c,"right")},lrpad:function(a,b,c){return j.pad(a,b,c,"both")},sprintf:i,vsprintf:function(a,b){return b.unshift(a),i.apply(null,b)},toNumber:function(a,b){var c=e(e(a).toFixed(~~b));return c===0&&""+a!="0"?Number.NaN:c},strRight:function(a,b){a+="",b=b!=null?""+b:b;var c=b?a.indexOf(b):-1;return c!=-1?a.slice(c+b.length,a.length):a},strRightBack:function(a,b){a+="",b=b!=null?""+b:b;var c=b?a.lastIndexOf(b):-1;return c!=-1?a.slice(c+b.length,a.length):a},strLeft:function(a,b){a+="",b=b!=null?""+b:b;var c=b?a.indexOf(b):-1;return c!=-1?a.slice(0,c):a},strLeftBack:function(a,b){a+="",b=b!=null?""+b:b;var c=a.lastIndexOf(b);return c!=-1?a.slice(0,c):a},toSentence:function(a,b,c){b||(b=", "),c||(c=" and ");var d=a.length,e="";for(var f=0;f<d;f++)e+=a[f],f===d-2?e+=c:f<d-1&&(e+=b);return e},slugify:function(a){var b="ąàáäâãćęèéëêìíïîłńòóöôõùúüûñçżź·/_:;",c="aaaaaaceeeeeiiiilnooooouuuunczz",d=new RegExp(h(b),"g");return a=(""+a).toLowerCase(),a=a.replace(d,function(a){var d=b.indexOf(a);return c.substring(d,d+1)||"-"}),j.trim(a.replace(/[^\w\s-]/g,"").replace(/[-\s]+/g,"-"),"-")},exports:function(){var a={};for(var b in this){if(!this.hasOwnProperty(b)||b=="include"||b=="contains"||b=="reverse")continue;a[b]=this[b]}return a},repeat:f};j.strip=j.trim,j.lstrip=j.ltrim,j.rstrip=j.rtrim,j.center=j.lrpad,j.rjust=j.lpad,j.ljust=j.rpad,j.contains=j.include,typeof exports!="undefined"?(typeof module!="undefined"&&module.exports&&(module.exports=j),exports._s=j):typeof define=="function"&&define.amd?define("underscore.string",function(){return j}):typeof a._!="undefined"?(a._.string=j,a._.str=a._.string):a._={string:j,str:j}})(this||window); |
@@ -15,8 +15,13 @@ // Underscore.string | ||
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(i, m) { | ||
for (var o = []; m > 0; o[--m] = i) {} | ||
return o.join(''); | ||
var strRepeat = function(str, qty, separator){ | ||
// ~~var — is the fastest available way to convert anything to Integer in javascript. | ||
// We'll use it extensively in this lib. | ||
str += ''; qty = ~~qty; | ||
for (var repeat = []; qty > 0; repeat[--qty] = str) {} | ||
return repeat.join(separator == null ? '' : separator); | ||
}; | ||
@@ -29,4 +34,4 @@ | ||
var defaultToWhiteSpace = function(characters){ | ||
if (characters) { | ||
return _s.escapeRegExp(characters); | ||
if (characters != null) { | ||
return '[' + _s.escapeRegExp(''+characters) + ']'; | ||
} | ||
@@ -36,11 +41,2 @@ return '\\s'; | ||
var sArgs = function(method){ | ||
return function(){ | ||
var args = slice(arguments); | ||
for(var i=0; i<args.length; i++) | ||
args[i] = args[i] == null ? '' : '' + args[i]; | ||
return method.apply(null, args); | ||
}; | ||
}; | ||
// sprintf() for JavaScript 0.7-beta1 | ||
@@ -79,3 +75,3 @@ // http://www.diveintojavascript.com/projects/javascript-sprintf | ||
if (!arg.hasOwnProperty(match[2][k])) { | ||
throw(sprintf('[_.sprintf] property "%s" does not exist', match[2][k])); | ||
throw new Error(sprintf('[_.sprintf] property "%s" does not exist', match[2][k])); | ||
} | ||
@@ -92,3 +88,3 @@ arg = arg[match[2][k]]; | ||
if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) { | ||
throw(sprintf('[_.sprintf] expecting number but found %s', get_type(arg))); | ||
throw new Error(sprintf('[_.sprintf] expecting number but found %s', get_type(arg))); | ||
} | ||
@@ -142,3 +138,3 @@ switch (match[8]) { | ||
else { | ||
throw('[_.sprintf] huh?'); | ||
throw new Error('[_.sprintf] huh?'); | ||
} | ||
@@ -148,3 +144,3 @@ } | ||
else { | ||
throw('[_.sprintf] huh?'); | ||
throw new Error('[_.sprintf] huh?'); | ||
} | ||
@@ -157,3 +153,3 @@ match[2] = field_list; | ||
if (arg_names === 3) { | ||
throw('[_.sprintf] mixing positional and named placeholders is not (yet) supported'); | ||
throw new Error('[_.sprintf] mixing positional and named placeholders is not (yet) supported'); | ||
} | ||
@@ -163,3 +159,3 @@ parse_tree.push(match); | ||
else { | ||
throw('[_.sprintf] huh?'); | ||
throw new Error('[_.sprintf] huh?'); | ||
} | ||
@@ -179,19 +175,21 @@ _fmt = _fmt.substring(match[0].length); | ||
var _s = { | ||
VERSION: '2.0.0', | ||
isBlank: sArgs(function(str){ | ||
isBlank: function(str){ | ||
return (/^\s*$/).test(str); | ||
}), | ||
}, | ||
stripTags: sArgs(function(str){ | ||
return str.replace(/<\/?[^>]+>/ig, ''); | ||
}), | ||
stripTags: function(str){ | ||
return (''+str).replace(/<\/?[^>]+>/ig, ''); | ||
}, | ||
capitalize : sArgs(function(str) { | ||
capitalize : function(str) { | ||
str += ''; | ||
return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase(); | ||
}), | ||
}, | ||
chop: sArgs(function(str, step){ | ||
step = parseNumber(step) || str.length; | ||
chop: function(str, step){ | ||
str = str+''; | ||
step = ~~step || str.length; | ||
var arr = []; | ||
@@ -203,103 +201,94 @@ for (var i = 0; i < str.length;) { | ||
return arr; | ||
}), | ||
}, | ||
clean: sArgs(function(str){ | ||
return _s.strip(str.replace(/\s+/g, ' ')); | ||
}), | ||
clean: function(str){ | ||
return _s.strip((''+str).replace(/\s+/g, ' ')); | ||
}, | ||
count: sArgs(function(str, substr){ | ||
var count = 0, index; | ||
for (var i=0; i < str.length;) { | ||
index = str.indexOf(substr, i); | ||
index >= 0 && count++; | ||
i = i + (index >= 0 ? index : 0) + substr.length; | ||
} | ||
return count; | ||
}), | ||
count: function(str, substr){ | ||
str += ''; substr += ''; | ||
return str.split(substr).length - 1; | ||
}, | ||
chars: sArgs(function(str) { | ||
return str.split(''); | ||
}), | ||
chars: function(str) { | ||
return (''+str).split(''); | ||
}, | ||
escapeHTML: sArgs(function(str) { | ||
return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>') | ||
escapeHTML: function(str) { | ||
return (''+str).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>') | ||
.replace(/"/g, '"').replace(/'/g, "'"); | ||
}), | ||
}, | ||
unescapeHTML: sArgs(function(str) { | ||
return str.replace(/</g, '<').replace(/>/g, '>') | ||
unescapeHTML: function(str) { | ||
return (''+str).replace(/</g, '<').replace(/>/g, '>') | ||
.replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); | ||
}), | ||
}, | ||
escapeRegExp: sArgs(function(str){ | ||
escapeRegExp: function(str){ | ||
// From MooTools core 1.2.4 | ||
return str.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1'); | ||
}), | ||
}, | ||
insert: sArgs(function(str, i, substr){ | ||
var arr = str.split(''); | ||
arr.splice(parseNumber(i), 0, substr); | ||
insert: function(str, i, substr){ | ||
var arr = (''+str).split(''); | ||
arr.splice(~~i, 0, ''+substr); | ||
return arr.join(''); | ||
}), | ||
}, | ||
include: sArgs(function(str, needle){ | ||
return str.indexOf(needle) !== -1; | ||
}), | ||
include: function(str, needle){ | ||
return (''+str).indexOf(needle) !== -1; | ||
}, | ||
join: sArgs(function(sep) { | ||
join: function(sep) { | ||
var args = slice(arguments); | ||
return args.join(args.shift()); | ||
}), | ||
}, | ||
lines: sArgs(function(str) { | ||
return str.split("\n"); | ||
}), | ||
lines: function(str) { | ||
return (''+str).split("\n"); | ||
}, | ||
reverse: sArgs(function(str){ | ||
reverse: function(str){ | ||
return Array.prototype.reverse.apply(String(str).split('')).join(''); | ||
}), | ||
}, | ||
splice: sArgs(function(str, i, howmany, substr){ | ||
var arr = str.split(''); | ||
arr.splice(parseNumber(i), parseNumber(howmany), substr); | ||
splice: function(str, i, howmany, substr){ | ||
var arr = (''+str).split(''); | ||
arr.splice(~~i, ~~howmany, substr); | ||
return arr.join(''); | ||
}), | ||
}, | ||
startsWith: sArgs(function(str, starts){ | ||
startsWith: function(str, starts){ | ||
str += ''; starts += ''; | ||
return str.length >= starts.length && str.substring(0, starts.length) === starts; | ||
}), | ||
}, | ||
endsWith: sArgs(function(str, ends){ | ||
endsWith: function(str, ends){ | ||
str += ''; ends += ''; | ||
return str.length >= ends.length && str.substring(str.length - ends.length) === ends; | ||
}), | ||
}, | ||
succ: sArgs(function(str){ | ||
succ: function(str){ | ||
str += ''; | ||
var arr = str.split(''); | ||
arr.splice(str.length-1, 1, String.fromCharCode(str.charCodeAt(str.length-1) + 1)); | ||
return arr.join(''); | ||
}), | ||
}, | ||
titleize: sArgs(function(str){ | ||
var arr = str.split(' '), | ||
word; | ||
for (var i=0; i < arr.length; i++) { | ||
word = arr[i].split(''); | ||
if(typeof word[0] !== 'undefined') word[0] = word[0].toUpperCase(); | ||
i+1 === arr.length ? arr[i] = word.join('') : arr[i] = word.join('') + ' '; | ||
} | ||
return arr.join(''); | ||
}), | ||
titleize: function(str){ | ||
return (''+str).replace(/\b./g, function(ch){ return ch.toUpperCase(); }); | ||
}, | ||
camelize: sArgs(function(str){ | ||
camelize: function(str){ | ||
return _s.trim(str).replace(/(\-|_|\s)+(.)?/g, function(match, separator, chr) { | ||
return chr ? chr.toUpperCase() : ''; | ||
}); | ||
}), | ||
}, | ||
underscored: function(str){ | ||
return _s.trim(str).replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/\-|\s+/g, '_').toLowerCase(); | ||
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\d])([A-Z]+)/g, '$1-$2').replace(/^([A-Z]+)/, '-$1').replace(/\_|\s+/g, '-').toLowerCase(); | ||
return _s.trim(str).replace(/[_\s]+/g, '-').replace(/([A-Z])/g, '-$1').replace(/-+/g, '-').toLowerCase(); | ||
}, | ||
@@ -311,3 +300,4 @@ | ||
trim: sArgs(function(str, characters){ | ||
trim: function(str, characters){ | ||
str += ''; | ||
if (!characters && nativeTrim) { | ||
@@ -317,20 +307,26 @@ return nativeTrim.call(str); | ||
characters = defaultToWhiteSpace(characters); | ||
return str.replace(new RegExp('\^[' + characters + ']+|[' + characters + ']+$', 'g'), ''); | ||
}), | ||
return str.replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), ''); | ||
}, | ||
ltrim: sArgs(function(str, characters){ | ||
ltrim: function(str, characters){ | ||
if (!characters && nativeTrimLeft) { | ||
return nativeTrimLeft.call(str); | ||
} | ||
characters = defaultToWhiteSpace(characters); | ||
return str.replace(new RegExp('\^[' + characters + ']+', 'g'), ''); | ||
}), | ||
return (''+str).replace(new RegExp('\^' + characters + '+', 'g'), ''); | ||
}, | ||
rtrim: sArgs(function(str, characters){ | ||
rtrim: function(str, characters){ | ||
if (!characters && nativeTrimRight) { | ||
return nativeTrimRight.call(str); | ||
} | ||
characters = defaultToWhiteSpace(characters); | ||
return str.replace(new RegExp('[' + characters + ']+$', 'g'), ''); | ||
}), | ||
return (''+str).replace(new RegExp(characters + '+$', 'g'), ''); | ||
}, | ||
truncate: sArgs(function(str, length, truncateStr){ | ||
truncateStr = truncateStr || '...'; | ||
length = parseNumber(length); | ||
return str.length > length ? str.slice(0,length) + truncateStr : str; | ||
}), | ||
truncate: function(str, length, truncateStr){ | ||
str += ''; truncateStr = truncateStr || '...'; | ||
length = ~~length; | ||
return str.length > length ? str.slice(0, length) + truncateStr : str; | ||
}, | ||
@@ -342,42 +338,40 @@ /** | ||
*/ | ||
prune: sArgs(function(str, length, pruneStr){ | ||
// Function to check word/digit chars including non-ASCII encodings. | ||
var isWordChar = function(c) { return ((c.toUpperCase() != c.toLowerCase()) || /[-_\d]/.test(c)); } | ||
prune: function(str, length, pruneStr){ | ||
str += ''; length = ~~length; | ||
pruneStr = pruneStr != null ? ''+pruneStr : '...'; | ||
var template = ''; | ||
var pruned = ''; | ||
var i = 0; | ||
var pruned, borderChar, template = str.replace(/\W/g, function(ch){ | ||
return (ch.toUpperCase() !== ch.toLowerCase()) ? 'A' : ' '; | ||
}); | ||
// Set default values | ||
pruneStr = pruneStr || '...'; | ||
length = parseNumber(length); | ||
borderChar = template.substring(length, length+1); | ||
// Convert to an ASCII string to avoid problems with unicode chars. | ||
for (i in str) { | ||
template += (isWordChar(str[i]))?'A':' '; | ||
} | ||
pruned = template.slice(0, length); | ||
// Check if we're in the middle of a word | ||
if( template.substring(length-1, length+1).search(/^\w\w$/) === 0 ) | ||
pruned = _s.rtrim(template.slice(0,length).replace(/([\W][\w]*)$/,'')); | ||
else | ||
pruned = _s.rtrim(template.slice(0,length)); | ||
if (borderChar && borderChar.match(/\S/)) | ||
pruned = pruned.replace(/\s\S+$/, ''); | ||
pruned = _s.rtrim(pruned); | ||
return (pruned+pruneStr).length > str.length ? str : str.substring(0, pruned.length)+pruneStr; | ||
}, | ||
pruned = pruned.replace(/\W+$/,''); | ||
return (pruned.length+pruneStr.length>str.length) ? str : str.substring(0, pruned.length)+pruneStr; | ||
}), | ||
words: function(str, delimiter) { | ||
return String(str).split(delimiter || " "); | ||
return _.trim(str, delimiter).split(delimiter || /\s+/); | ||
}, | ||
pad: sArgs(function(str, length, padStr, type) { | ||
var padding = '', | ||
padlen = 0; | ||
pad: function(str, length, padStr, type) { | ||
str += ''; | ||
var padding = '', padlen = 0; | ||
length = parseNumber(length); | ||
if (!padStr) { padStr = ' '; } | ||
else if (padStr.length > 1) { padStr = padStr.charAt(0); } | ||
length = ~~length; | ||
if (!padStr) { | ||
padStr = ' '; | ||
} else if (padStr.length > 1) { | ||
padStr = padStr.charAt(0); | ||
} | ||
switch(type) { | ||
@@ -403,3 +397,3 @@ case 'right': | ||
return str; | ||
}), | ||
}, | ||
@@ -426,26 +420,59 @@ lpad: function(str, length, padStr) { | ||
toNumber: function(str, decimals) { | ||
var num = parseNumber(parseNumber(str).toFixed(parseNumber(decimals))); | ||
return (!(num === 0 && (str !== "0" && str !== 0))) ? num : Number.NaN; | ||
var num = parseNumber(parseNumber(str).toFixed(~~decimals)); | ||
return num === 0 && ''+str !== '0' ? Number.NaN : num; | ||
}, | ||
strRight: sArgs(function(sourceStr, sep){ | ||
var pos = (!sep) ? -1 : sourceStr.indexOf(sep); | ||
return (pos != -1) ? sourceStr.slice(pos+sep.length, sourceStr.length) : sourceStr; | ||
}), | ||
strRight: function(str, sep){ | ||
str += ''; sep = sep != null ? ''+sep : sep; | ||
var pos = (!sep) ? -1 : str.indexOf(sep); | ||
return (pos != -1) ? str.slice(pos+sep.length, str.length) : str; | ||
}, | ||
strRightBack: sArgs(function(sourceStr, sep){ | ||
var pos = (!sep) ? -1 : sourceStr.lastIndexOf(sep); | ||
return (pos != -1) ? sourceStr.slice(pos+sep.length, sourceStr.length) : sourceStr; | ||
}), | ||
strRightBack: function(str, sep){ | ||
str += ''; sep = sep != null ? ''+sep : sep; | ||
var pos = (!sep) ? -1 : str.lastIndexOf(sep); | ||
return (pos != -1) ? str.slice(pos+sep.length, str.length) : str; | ||
}, | ||
strLeft: sArgs(function(sourceStr, sep){ | ||
var pos = (!sep) ? -1 : sourceStr.indexOf(sep); | ||
return (pos != -1) ? sourceStr.slice(0, pos) : sourceStr; | ||
}), | ||
strLeft: function(str, sep){ | ||
str += ''; sep = sep != null ? ''+sep : sep; | ||
var pos = (!sep) ? -1 : str.indexOf(sep); | ||
return (pos != -1) ? str.slice(0, pos) : str; | ||
}, | ||
strLeftBack: sArgs(function(sourceStr, sep){ | ||
var pos = sourceStr.lastIndexOf(sep); | ||
return (pos != -1) ? sourceStr.slice(0, pos) : sourceStr; | ||
}), | ||
strLeftBack: function(str, sep){ | ||
str += ''; sep = sep != null ? ''+sep : sep; | ||
var pos = str.lastIndexOf(sep); | ||
return (pos != -1) ? str.slice(0, pos) : str; | ||
}, | ||
toSentence: function(array, separator, lastSeparator) { | ||
separator || (separator = ', '); | ||
lastSeparator || (lastSeparator = ' and '); | ||
var length = array.length, str = ''; | ||
for (var i = 0; i < length; i++) { | ||
str += array[i]; | ||
if (i === (length - 2)) { str += lastSeparator; } | ||
else if (i < (length - 1)) { str += separator; } | ||
} | ||
return str; | ||
}, | ||
slugify: function(str) { | ||
var from = "ąàáäâãćęèéëêìíïîłńòóöôõùúüûñçżź·/_:;", | ||
to = "aaaaaaceeeeeiiiilnooooouuuunczz", | ||
regex = new RegExp(defaultToWhiteSpace(from), 'g'); | ||
str = (''+str).toLowerCase(); | ||
str = str.replace(regex, function(ch){ | ||
var index = from.indexOf(ch); | ||
return to.substring(index, index+1) || '-'; | ||
}); | ||
return _s.trim(str.replace(/[^\w\s-]/g, '').replace(/[-\s]+/g, '-'), '-'); | ||
}, | ||
exports: function() { | ||
@@ -460,3 +487,5 @@ var result = {}; | ||
return result; | ||
} | ||
}, | ||
repeat: strRepeat | ||
@@ -471,4 +500,4 @@ }; | ||
_s.center = _s.lrpad; | ||
_s.ljust = _s.lpad; | ||
_s.rjust = _s.rpad; | ||
_s.rjust = _s.lpad; | ||
_s.ljust = _s.rpad; | ||
_s.contains = _s.include; | ||
@@ -484,2 +513,8 @@ | ||
} else if (typeof define === 'function' && define.amd) { | ||
// Register as a named module with AMD. | ||
define('underscore.string', function() { | ||
return _s; | ||
}); | ||
// Integrate with Underscore.js | ||
@@ -486,0 +521,0 @@ } else if (typeof root._ !== 'undefined') { |
{ | ||
"name": "underscore.string", | ||
"version": "2.0.0", | ||
"version": "2.1.0", | ||
"description": "String manipulation extensions for Underscore.js javascript library.", | ||
@@ -27,3 +27,2 @@ "homepage": "http://epeli.github.com/underscore.string/", | ||
}, | ||
"dependencies": [], | ||
"repository": { | ||
@@ -30,0 +29,0 @@ "type": "git", |
@@ -134,2 +134,6 @@ (function() { | ||
JSLitmus.test('slugify', function(){ | ||
_("Un éléphant à l'orée du bois").slugify(); | ||
}); | ||
})(); |
@@ -25,2 +25,5 @@ $(document).ready(function() { | ||
equals(_("c:\\").trim('\\'), "c:"); | ||
equals(_(123).trim(), '123'); | ||
equals(_(123).trim(3), '12'); | ||
}); | ||
@@ -40,2 +43,4 @@ | ||
equals(_("_-foobar-_").ltrim("_-"), "foobar-_"); | ||
equals(_(123).ltrim(1), '23'); | ||
}); | ||
@@ -56,2 +61,4 @@ | ||
equals(_("_-foobar-_").rtrim("_-"), "_-foobar"); | ||
equals(_(123).rtrim(3), '12'); | ||
}); | ||
@@ -145,2 +152,3 @@ | ||
equals(_('Hello world').count('foo'), 0); | ||
equals(_('x.xx....x.x').count('x'), 5); | ||
equals(_(12345).count(1), 1); | ||
@@ -195,4 +203,10 @@ equals(_(11345).count(1), 2); | ||
equals(_('TheDasherizeStringMethod').dasherize(), '-the-dasherize-string-method'); | ||
equals(_('thisIsATest').dasherize(), 'this-is-a-test'); | ||
equals(_('this Is A Test').dasherize(), 'this-is-a-test'); | ||
equals(_('thisIsATest123').dasherize(), 'this-is-a-test123'); | ||
equals(_('123thisIsATest').dasherize(), '123this-is-a-test'); | ||
equals(_('the dasherize string method').dasherize(), 'the-dasherize-string-method'); | ||
equals(_('the dasherize string method ').dasherize(), 'the-dasherize-string-method'); | ||
equals(_('téléphone').dasherize(), 'téléphone'); | ||
equals(_('foo$bar').dasherize(), 'foo$bar'); | ||
equals(_(123).dasherize(), '123'); | ||
@@ -225,2 +239,10 @@ }); | ||
equals(_('Hello world').prune(22), 'Hello world'); | ||
equals(_('Привет, жестокий мир').prune(6, ' read more'), 'Привет read more'); | ||
equals(_('Привет, мир').prune(6, 'read a lot more'), 'Привет, мир'); | ||
equals(_('Привет, мир').prune(6), 'Привет...'); | ||
equals(_('Привет, мир').prune(8), 'Привет...'); | ||
equals(_('Привет, жестокий мир').prune(16), 'Привет, жестокий...'); | ||
equals(_('Привет, мир').prune(22), 'Привет, мир'); | ||
equals(_(123).prune(10), '123'); | ||
equals(_(123).prune(1,1), '11'); | ||
}); | ||
@@ -242,3 +264,3 @@ | ||
equals(_(5).escapeHTML(), '5'); | ||
equals(_(undefined).escapeHTML(), ''); | ||
// equals(_(undefined).escapeHTML(), ''); | ||
}); | ||
@@ -251,3 +273,3 @@ | ||
equals(_(5).unescapeHTML(), '5'); | ||
equals(_(undefined).unescapeHTML(), ''); | ||
// equals(_(undefined).unescapeHTML(), ''); | ||
}); | ||
@@ -257,2 +279,3 @@ | ||
equals(_("I love you!").words().length, 3); | ||
equals(_(" I love you! ").words().length, 3); | ||
equals(_("I_love_you!").words('_').length, 3); | ||
@@ -367,2 +390,26 @@ equals(_("I-love-you!").words(/-/).length, 3); | ||
test('Strings: toSentence', function() { | ||
equals(_.toSentence(['jQuery']), 'jQuery', 'array with a single element'); | ||
equals(_.toSentence(['jQuery', 'MooTools']), 'jQuery and MooTools', 'array with two elements'); | ||
equals(_.toSentence(['jQuery', 'MooTools', 'Prototype']), 'jQuery, MooTools and Prototype', 'array with three elements'); | ||
equals(_.toSentence(['jQuery', 'MooTools', 'Prototype', 'YUI']), 'jQuery, MooTools, Prototype and YUI', 'array with multiple elements'); | ||
equals(_.toSentence(['jQuery', 'MooTools', 'Prototype'], ',', ' or '), 'jQuery,MooTools or Prototype', 'handles custom separators'); | ||
}); | ||
test('Strings: slugify', function() { | ||
equals(_("Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/").slugify(), "jack-jill-like-numbers-123-and-4-and-silly-characters"); | ||
equals(_("Un éléphant à l'orée du bois").slugify(), "un-elephant-a-loree-du-bois"); | ||
equals(_("I know latin characters: á í ó ú ç ã õ ñ ü").slugify(), "i-know-latin-characters-a-i-o-u-c-a-o-n-u"); | ||
equals(_("I am a word too, even though I am but a single letter: i!").slugify(), "i-am-a-word-too-even-though-i-am-but-a-single-letter-i"); | ||
}); | ||
test('Strings: repeat', function() { | ||
equals(_.repeat('foo'), ''); | ||
equals(_.repeat('foo', 3), 'foofoofoo'); | ||
equals(_.repeat('foo', '3'), 'foofoofoo'); | ||
equals(_.repeat(123, 2), '123123'); | ||
equals(_.repeat(1234, 2, '*'), '1234*1234'); | ||
equals(_.repeat(1234, 2, 5), '123451234'); | ||
}); | ||
}); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
307614
29
5789
652
1