Socket
Socket
Sign inDemoInstall

@olton/string

Package Overview
Dependencies
63
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.4.3 to 0.4.4

1440

dist/string.js

@@ -65,7 +65,32 @@ /**

*/
const REGEXP_WORD = new RegExp('(?:[' + upperCaseLetter + '][' + diacriticalMark + ']*)?(?:[' + lowerCaseLetter + '][' + diacriticalMark + ']*)+|\
(?:[' + upperCaseLetter + '][' + diacriticalMark + ']*)+(?![' + lowerCaseLetter + '])|\
[' + digit + ']+|\
[' + dingbatBlock + ']|\
[^' + nonCharacter + generalPunctuationBlock + whitespace + ']+', 'g');
const REGEXP_WORD = new RegExp(
'(?:[' +
upperCaseLetter +
'][' +
diacriticalMark +
']*)?(?:[' +
lowerCaseLetter +
'][' +
diacriticalMark +
']*)+|\
(?:[' +
upperCaseLetter +
'][' +
diacriticalMark +
']*)+(?![' +
lowerCaseLetter +
'])|\
[' +
digit +
']+|\
[' +
dingbatBlock +
']|\
[^' +
nonCharacter +
generalPunctuationBlock +
whitespace +
']+',
'g'
);

@@ -85,3 +110,5 @@ /**

*/
const REGEXP_ALPHA_DIGIT = new RegExp('^((?:[' + lowerCaseLetter + upperCaseLetter + '][' + diacriticalMark + ']*)|[' + digit + '])+$');
const REGEXP_ALPHA_DIGIT = new RegExp(
'^((?:[' + lowerCaseLetter + upperCaseLetter + '][' + diacriticalMark + ']*)|[' + digit + '])+$'
);

@@ -94,10 +121,10 @@ /**

const toStr = (val, def = "") => {
if (!val) return def;
if (typeof val === "string") return val;
if (Array.isArray(val)) return val.join("");
return JSON.stringify(val);
if (!val) return def;
if (typeof val === "string") return val;
if (Array.isArray(val)) return val.join("");
return JSON.stringify(val);
};
const nvl = (a, b) => {
return typeof a === "undefined" || a === null ? b : a;
return (typeof a === "undefined" || a === null) ? b : a
};

@@ -109,33 +136,35 @@

const words = (s, pattern, flags) => {
let regexp;
if (!pattern) {
regexp = REGEXP_EXTENDED_ASCII.test(s) ? REGEXP_LATIN_WORD : REGEXP_WORD;
} else if (pattern instanceof RegExp) {
regexp = pattern;
} else {
regexp = new RegExp(pattern, nvl(flags, ''));
}
return nvl(toStr(s).match(regexp), []);
let regexp;
if (!pattern) {
regexp = REGEXP_EXTENDED_ASCII.test(s) ? REGEXP_LATIN_WORD : REGEXP_WORD;
} else if (pattern instanceof RegExp) {
regexp = pattern;
} else {
regexp = new RegExp(pattern, nvl(flags, ''));
}
return nvl(toStr(s).match(regexp), []);
};
const capitalize = (s, strong = false) => {
let _s = toStr(s);
let last = _s.substr(1);
return _s.substr(0, 1).toUpperCase() + (strong ? last.toLowerCase() : last);
let _s = toStr(s);
let last = (_s).substr(1);
return (_s).substr(0, 1).toUpperCase() + (strong ? last.toLowerCase() : last)
};
const camelCase = s => {
return words(toStr(s)).map((el, i) => {
return i === 0 ? el.toLowerCase() : capitalize(el);
}).join("");
return words(toStr(s)).map( (el, i) => {
return i === 0 ? el.toLowerCase() : capitalize(el)
} ).join("")
};
const dashedName = s => words(toStr(s)).map(el => el.toLowerCase()).join("-");
const dashedName = s => words(toStr(s)).map( (el) => el.toLowerCase() ).join("-");
const decapitalize = s => {
let _s = toStr(s);
return _s.substr(0, 1).toLowerCase() + _s.substr(1);
let _s = toStr(s);
return (_s).substr(0, 1).toLowerCase() + (_s).substr(1)
};
const kebab = (s, joinWith = '-') => words(toStr(s)).map(el => el.toLowerCase()).join(joinWith);
const kebab = (s, joinWith = '-') => words(toStr(s)).map( el => el.toLowerCase() ).join(joinWith);

@@ -147,3 +176,3 @@ const lower = s => toStr(s).toLowerCase();

* */
const chars$1 = (s, ignore = []) => toStr(s).split("").filter(el => !ignore.includes(el));
const chars$1 = (s, ignore = []) => (toStr(s)).split("").filter( (el) => !ignore.includes(el));

@@ -154,5 +183,4 @@ const reverse = (s, ignore) => chars$1(toStr(s), ignore).reverse().join("");

let _a = [...a];
let i = _a.length,
t,
r;
let i = _a.length, t, r;
while (0 !== i) {

@@ -165,2 +193,3 @@ r = Math.floor(Math.random() * i);

}
return _a;

@@ -171,19 +200,22 @@ };

const snake = s => words(toStr(s)).map(el => el.toLowerCase()).join("_");
const snake = s => words(toStr(s)).map( el => el.toLowerCase() ).join("_");
const _swap = (swapped, char) => {
const lc = char.toLowerCase();
const uc = char.toUpperCase();
return swapped + (char === lc ? uc : lc);
const lc = char.toLowerCase();
const uc = char.toUpperCase();
return swapped + (char === lc ? uc : lc)
};
const swap = s => toStr(s).split("").reduce(_swap, '');
const title = (s, noSplit, sep = "") => {
let _s = toStr(s);
const regexp = REGEXP_EXTENDED_ASCII.test(_s) ? REGEXP_LATIN_WORD : REGEXP_WORD;
const noSplitArray = Array.isArray(noSplit) ? noSplit : typeof noSplit !== "string" ? [] : noSplit.split(sep);
return s.replace(regexp, (w, i) => {
const isNoSplit = i && noSplitArray.includes(_s[i - 1]);
return isNoSplit ? lower(w) : capitalize(w);
});
let _s = toStr(s);
const regexp = REGEXP_EXTENDED_ASCII.test(_s) ? REGEXP_LATIN_WORD : REGEXP_WORD;
const noSplitArray = Array.isArray(noSplit) ? noSplit : typeof noSplit !== "string" ? [] : noSplit.split(sep);
return s.replace(regexp, (w, i) => {
const isNoSplit = i && noSplitArray.includes(_s[i - 1]);
return isNoSplit ? lower(w) : capitalize(w);
})
};

@@ -199,9 +231,11 @@

const uniqueArray = (a = []) => {
let _a = [...a];
for (let i = 0; i < _a.length; ++i) {
for (let j = i + 1; j < _a.length; ++j) {
if (_a[i] === _a[j]) _a.splice(j--, 1);
let _a = [...a];
for (let i = 0; i < _a.length; ++i) {
for (let j = i + 1; j < _a.length; ++j) {
if (_a[i] === _a[j])
_a.splice(j--, 1);
}
}
}
return _a;
return _a;
};

@@ -213,5 +247,5 @@

const countSubstr = (s, sub = "") => {
let _s = toStr(s);
let _sub = toStr(sub);
return _s === '' || _sub === '' ? 0 : _s.split(_sub).length - 1;
let _s = toStr(s);
let _sub = toStr(sub);
return _s === '' || _sub === '' ? 0 : _s.split(_sub).length - 1;
};

@@ -223,26 +257,30 @@

const escapeCharactersMap = {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;',
"'": '&#x27;',
'`': '&#x60;'
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;',
"'": '&#x27;',
'`': '&#x60;',
};
function replaceSpecialCharacter(character) {
return escapeCharactersMap[character];
return escapeCharactersMap[character];
}
const escapeHtml = s => toStr(s).replace(REGEXP_HTML_SPECIAL_CHARACTERS, replaceSpecialCharacter);
const unescapeCharsMap = {
'<': /(&lt;)|(&#x0*3c;)|(&#0*60;)/gi,
'>': /(&gt;)|(&#x0*3e;)|(&#0*62;)/gi,
'&': /(&amp;)|(&#x0*26;)|(&#0*38;)/gi,
'"': /(&quot;)|(&#x0*22;)|(&#0*34;)/gi,
"'": /(&#x0*27;)|(&#0*39;)/gi,
'`': /(&#x0*60;)|(&#0*96;)/gi
'<': /(&lt;)|(&#x0*3c;)|(&#0*60;)/gi,
'>': /(&gt;)|(&#x0*3e;)|(&#0*62;)/gi,
'&': /(&amp;)|(&#x0*26;)|(&#0*38;)/gi,
'"': /(&quot;)|(&#x0*22;)|(&#0*34;)/gi,
"'": /(&#x0*27;)|(&#0*39;)/gi,
'`': /(&#x0*60;)|(&#0*96;)/gi,
};
const chars = Object.keys(unescapeCharsMap);
function reduceUnescapedString(string, key) {
return string.replace(unescapeCharsMap[key], key);
return string.replace(unescapeCharsMap[key], key);
}
const unescapeHtml = s => chars.reduce(reduceUnescapedString, toStr(s));

@@ -276,11 +314,11 @@

const clip = (val, min, max = MAX_SAFE_INTEGER) => {
if (val < min) return min;
if (val > max) return max;
return val;
if (val < min) return min;
if (val > max) return max;
return val;
};
const toInt = val => {
if (val === Infinity) return MAX_SAFE_INTEGER;
if (val === -Infinity) return -MAX_SAFE_INTEGER;
return ~~val;
if (val === Infinity) return MAX_SAFE_INTEGER;
if (val === -Infinity) return -MAX_SAFE_INTEGER;
return ~~val;
};

@@ -294,7 +332,9 @@

let _len = !len ? _s.length : clip(toInt(len), 0, MAX_SAFE_INTEGER);
return substring(_s, 0, _len) + (_s.length === _len ? '' : end);
return substring(_s, 0, _len) + (_s.length === _len ? '' : end)
};
const truncateWithAlign = (s, len = 0, end = '...') => {
const truncatedText = truncate(s, len, '');
return truncatedText.slice(s, truncatedText.lastIndexOf(" ")) + end;
return truncatedText.slice(s, truncatedText.lastIndexOf(" ")) + end
};

@@ -309,6 +349,10 @@

let len = Math.round(_s.length / parts);
for (let i = 0; i < parts; i++) {
res.push(substring(_s, i * len, len));
for(let i = 0; i < parts; i++) {
res.push(
substring(_s, i * len, len)
);
}
return res;
return res
};

@@ -320,68 +364,78 @@

const prune = (s, len = 0, end = "") => {
let _s = toStr(s);
let _len = !len ? _s.length : clip(toInt(len), 0, MAX_SAFE_INTEGER);
let _truncatedLen = 0;
const pattern = REGEXP_EXTENDED_ASCII.test(_s) ? REGEXP_LATIN_WORD : REGEXP_WORD;
_s.replace(pattern, (word, offset) => {
const wordLength = offset + word.length;
if (wordLength <= _len - end.length) {
_truncatedLen = wordLength;
}
});
return _s.substring(0, _truncatedLen) + end;
let _s = toStr(s);
let _len = !len ? _s.length : clip(toInt(len), 0, MAX_SAFE_INTEGER);
let _truncatedLen = 0;
const pattern = REGEXP_EXTENDED_ASCII.test(_s) ? REGEXP_LATIN_WORD : REGEXP_WORD;
_s.replace(pattern, (word, offset) => {
const wordLength = offset + word.length;
if (wordLength <= _len - end.length) {
_truncatedLen = wordLength;
}
});
return _s.substring(0, _truncatedLen) + end;
};
const repeat = (s, times = 0) => {
let _s = toStr(s);
let _times = !times ? _s.length : clip(toInt(times), 0, MAX_SAFE_INTEGER);
const _origin = _s;
if (times === 0) {
return "";
}
for (let i = 0; i < _times - 1; i++) {
_s += _origin;
}
return _s;
let _s = toStr(s);
let _times = !times ? _s.length : clip(toInt(times), 0, MAX_SAFE_INTEGER);
const _origin = _s;
if (times === 0) {
return "";
}
for(let i = 0; i < _times - 1; i++) {
_s += _origin;
}
return _s
};
const padBuilder = (pad, len = 0) => {
const padLength = pad.length;
const length = len - padLength;
return repeat(pad, length + 1).substring(0, len);
const padLength = pad.length;
const length = len - padLength;
return repeat(pad, length + 1).substring(0, len)
};
const _pad = (s, pad = "", len = 0, left = false) => {
let _s = toStr(s);
let _len = !len ? _s.length : clip(toInt(len), 0, MAX_SAFE_INTEGER);
let _padLen = pad.length;
let _paddingLen = _len - _s.length;
let _sideLen = _paddingLen;
if (_paddingLen <= 0 || _padLen === 0) {
return _s;
}
let pads = padBuilder(pad, _sideLen);
return left ? pads + _s : _s + pads;
let _s = toStr(s);
let _len = !len ? _s.length : clip(toInt(len), 0, MAX_SAFE_INTEGER);
let _padLen = pad.length;
let _paddingLen = _len - _s.length;
let _sideLen = _paddingLen;
if (_paddingLen <= 0 || _padLen === 0) {return _s}
let pads = padBuilder(pad, _sideLen);
return left ? pads + _s : _s + pads
};
const lpad = (s, pad = ' ', len = 0) => {
return _pad(s, pad, len, true);
return _pad(s, pad, len, true)
};
const rpad = (s, pad = ' ', len = 0) => {
return _pad(s, pad, len, false);
return _pad(s, pad, len, false)
};
const pad = (s, pad = '', len = 0) => {
let _s = toStr(s);
let _len = !len ? _s.length : clip(toInt(len), 0, MAX_SAFE_INTEGER);
let _padLen = pad.length;
let _paddingLen = _len - _s.length;
let _sideLen = toInt(_paddingLen / 2); //?
let _remainingLen = _paddingLen % 2; //?
let _s = toStr(s);
let _len = !len ? _s.length : clip(toInt(len), 0, MAX_SAFE_INTEGER);
let _padLen = pad.length;
let _paddingLen = _len - _s.length;
let _sideLen = toInt(_paddingLen / 2); //?
let _remainingLen = _paddingLen % 2; //?
if (_paddingLen <= 0 || _padLen === 0) {
return _s;
}
return padBuilder(pad, _sideLen) + _s + padBuilder(pad, _sideLen + _remainingLen); //?
if (_paddingLen <= 0 || _padLen === 0) {return _s}
return padBuilder(pad, _sideLen) + _s + padBuilder(pad, _sideLen + _remainingLen) //?
};
const insert = (s, sbj = '', pos = 0) => {
let _s = toStr(s);
return _s.substring(0, pos) + sbj + _s.substring(pos);
let _s = toStr(s);
return _s.substring(0, pos) + sbj + _s.substring(pos)
};

@@ -391,42 +445,47 @@

const reduceRight = Array.prototype.reduceRight;
const trim = (s, ws) => ltrim(rtrim(s, ws), ws);
const ltrim = (s, ws) => {
let _s = toStr(s);
if (!ws) {
return _s.replace(REGEXP_TRIM_LEFT, '');
}
if (ws === '' || _s === '') {
return _s;
}
if (typeof ws !== "string") {
ws = '';
}
let match = true;
return reduce.call(_s, (trimmed, char) => {
if (match && ws.includes(char)) {
return trimmed;
}
match = false;
return trimmed + char;
}, '');
let _s = toStr(s);
if (!ws) {return _s.replace(REGEXP_TRIM_LEFT, '')}
if (ws === '' || _s === '') {return _s}
if (typeof ws !== "string") {ws = '';}
let match = true;
return reduce.call(
_s,
(trimmed, char) => {
if (match && ws.includes(char)) {
return trimmed;
}
match = false;
return trimmed + char
},
''
);
};
const rtrim = (s, ws) => {
let _s = toStr(s);
if (!ws) {
return _s.replace(REGEXP_TRIM_RIGHT, '');
}
if (ws === '' || _s === '') {
return _s;
}
if (typeof ws !== "string") {
ws = '';
}
let match = true;
return reduceRight.call(_s, (trimmed, char) => {
if (match && ws.includes(char)) {
return trimmed;
}
match = false;
return char + trimmed;
}, '');
let _s = toStr(s);
if (!ws) {return _s.replace(REGEXP_TRIM_RIGHT, '')}
if (ws === '' || _s === '') {return _s}
if (typeof ws !== "string") {ws = '';}
let match = true;
return reduceRight.call(
_s,
(trimmed, char) => {
if (match && ws.includes(char)) {
return trimmed
}
match = false;
return char + trimmed
},
''
);
};

@@ -453,8 +512,10 @@

const stripTagsAll = s => toStr(s).replace(REGEXP_TAGS, '');
const stripTags = (s, allowed = []) => {
let _s = toStr(s);
let tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
return _s.replace(tags, ($0, $1) => {
return allowed.includes($1) ? $0 : '';
});
let _s = toStr(s);
let tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
return _s.replace(tags, ($0, $1) => {
return allowed.includes($1) ? $0 : ''
})
};

@@ -470,188 +531,199 @@

const re = {
not_string: /[^s]/,
not_bool: /[^t]/,
not_type: /[^T]/,
not_primitive: /[^v]/,
number: /[diefg]/,
numeric_arg: /[bcdiefguxX]/,
json: /[j]/,
not_json: /[^j]/,
text: /^[^\x25]+/,
modulo: /^\x25{2}/,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
key: /^([a-z_][a-z_\d]*)/i,
key_access: /^\.([a-z_][a-z_\d]*)/i,
index_access: /^\[(\d+)\]/,
sign: /^[+-]/
not_string: /[^s]/,
not_bool: /[^t]/,
not_type: /[^T]/,
not_primitive: /[^v]/,
number: /[diefg]/,
numeric_arg: /[bcdiefguxX]/,
json: /[j]/,
not_json: /[^j]/,
text: /^[^\x25]+/,
modulo: /^\x25{2}/,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
key: /^([a-z_][a-z_\d]*)/i,
key_access: /^\.([a-z_][a-z_\d]*)/i,
index_access: /^\[(\d+)\]/,
sign: /^[+-]/
};
function sprintf_format(parse_tree, argv) {
let cursor = 1,
tree_length = parse_tree.length,
arg,
output = '',
ph,
pad,
pad_character,
pad_length,
is_positive,
sign;
for (let i = 0; i < tree_length; i++) {
if (typeof parse_tree[i] === 'string') {
output += parse_tree[i];
} else if (typeof parse_tree[i] === 'object') {
ph = parse_tree[i]; // convenience purposes only
if (ph.keys) {
// keyword argument
arg = argv[cursor];
for (let k = 0; k < ph.keys.length; k++) {
if (typeof arg === "undefined") {
throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
}
arg = arg[ph.keys[k]];
let cursor = 1, tree_length = parse_tree.length, arg, output = '', ph, pad, pad_character, pad_length, is_positive, sign;
for (let i = 0; i < tree_length; i++) {
if (typeof parse_tree[i] === 'string') {
output += parse_tree[i];
}
} else if (ph.param_no) {
// positional argument (explicit)
arg = argv[ph.param_no];
} else {
// positional argument (implicit)
arg = argv[cursor++];
}
if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
arg = arg();
}
if (re.numeric_arg.test(ph.type) && typeof arg !== 'number' && isNaN(arg)) {
throw new TypeError(sprintf('[sprintf] expecting number but found %T'));
}
if (re.number.test(ph.type)) {
is_positive = arg >= 0;
}
switch (ph.type) {
case 'b':
arg = parseInt(arg, 10).toString(2);
break;
case 'c':
arg = String.fromCharCode(parseInt(arg, 10));
break;
case 'd':
case 'i':
arg = parseInt(arg, 10);
break;
case 'j':
arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
break;
case 'e':
arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
break;
case 'f':
arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
break;
case 'g':
arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
break;
case 'o':
arg = (parseInt(arg, 10) >>> 0).toString(8);
break;
case 's':
arg = String(arg);
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case 't':
arg = String(!!arg);
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case 'T':
arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case 'u':
arg = parseInt(arg, 10) >>> 0;
break;
case 'v':
arg = arg.valueOf();
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case 'x':
arg = (parseInt(arg, 10) >>> 0).toString(16);
break;
case 'X':
arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
break;
}
if (re.json.test(ph.type)) {
output += arg;
} else {
if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
sign = is_positive ? '+' : '-';
arg = arg.toString().replace(re.sign, '');
} else {
sign = '';
else if (typeof parse_tree[i] === 'object') {
ph = parse_tree[i]; // convenience purposes only
if (ph.keys) { // keyword argument
arg = argv[cursor];
for (let k = 0; k < ph.keys.length; k++) {
if (typeof arg === "undefined") {
throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
}
arg = arg[ph.keys[k]];
}
}
else if (ph.param_no) { // positional argument (explicit)
arg = argv[ph.param_no];
}
else { // positional argument (implicit)
arg = argv[cursor++];
}
if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
arg = arg();
}
if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
throw new TypeError(sprintf('[sprintf] expecting number but found %T'))
}
if (re.number.test(ph.type)) {
is_positive = arg >= 0;
}
switch (ph.type) {
case 'b':
arg = parseInt(arg, 10).toString(2);
break
case 'c':
arg = String.fromCharCode(parseInt(arg, 10));
break
case 'd':
case 'i':
arg = parseInt(arg, 10);
break
case 'j':
arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
break
case 'e':
arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
break
case 'f':
arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
break
case 'g':
arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
break
case 'o':
arg = (parseInt(arg, 10) >>> 0).toString(8);
break
case 's':
arg = String(arg);
arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
break
case 't':
arg = String(!!arg);
arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
break
case 'T':
arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
break
case 'u':
arg = parseInt(arg, 10) >>> 0;
break
case 'v':
arg = arg.valueOf();
arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
break
case 'x':
arg = (parseInt(arg, 10) >>> 0).toString(16);
break
case 'X':
arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
break
}
if (re.json.test(ph.type)) {
output += arg;
}
else {
if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
sign = is_positive ? '+' : '-';
arg = arg.toString().replace(re.sign, '');
}
else {
sign = '';
}
pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ';
pad_length = ph.width - (sign + arg).length;
pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '';
output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg);
}
}
pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ';
pad_length = ph.width - (sign + arg).length;
pad = ph.width ? pad_length > 0 ? pad_character.repeat(pad_length) : '' : '';
output += ph.align ? sign + arg + pad : pad_character === '0' ? sign + pad + arg : pad + sign + arg;
}
}
}
return output;
return output
}
const sprintf_cache = Object.create(null);
function sprintf_parse(fmt) {
if (sprintf_cache[fmt]) {
return sprintf_cache[fmt];
}
let _fmt = fmt,
match,
parse_tree = [],
arg_names = 0;
while (_fmt) {
if ((match = re.text.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
} else if ((match = re.modulo.exec(_fmt)) !== null) {
parse_tree.push('%');
} else if ((match = re.placeholder.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
let field_list = [],
replacement_field = match[2],
field_match = [];
if ((field_match = re.key.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = re.key_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
} else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
} else {
throw new SyntaxError('[sprintf] failed to parse named argument key');
if (sprintf_cache[fmt]) {
return sprintf_cache[fmt]
}
let _fmt = fmt, match, parse_tree = [], arg_names = 0;
while (_fmt) {
if ((match = re.text.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
}
else if ((match = re.modulo.exec(_fmt)) !== null) {
parse_tree.push('%');
}
else if ((match = re.placeholder.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
let field_list = [], replacement_field = match[2], field_match = [];
if ((field_match = re.key.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = re.key_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else {
throw new SyntaxError('[sprintf] failed to parse named argument key')
}
}
}
else {
throw new SyntaxError('[sprintf] failed to parse named argument key')
}
match[2] = field_list;
}
}
} else {
throw new SyntaxError('[sprintf] failed to parse named argument key');
else {
arg_names |= 2;
}
if (arg_names === 3) {
throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
}
parse_tree.push(
{
placeholder: match[0],
param_no: match[1],
keys: match[2],
sign: match[3],
pad_char: match[4],
align: match[5],
width: match[6],
precision: match[7],
type: match[8]
}
);
}
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({
placeholder: match[0],
param_no: match[1],
keys: match[2],
sign: match[3],
pad_char: match[4],
align: match[5],
width: match[6],
precision: match[7],
type: match[8]
});
} else {
throw new SyntaxError('[sprintf] unexpected placeholder');
else {
throw new SyntaxError('[sprintf] unexpected placeholder')
}
_fmt = _fmt.substring(match[0].length);
}
_fmt = _fmt.substring(match[0].length);
}
return sprintf_cache[fmt] = parse_tree;
return sprintf_cache[fmt] = parse_tree
}
const sprintf = key => sprintf_format(sprintf_parse(key), arguments);

@@ -663,11 +735,17 @@ const vsprintf = (fmt, argv) => sprintf.apply(null, [fmt].concat(argv || []));

const split = (str, sep = undefined, limit = undefined, trim = true) => {
return toStr(str).split(sep, limit).map(el => trim ? el.trim() : el).filter(el => trim ? !isEmpty(el) : true);
return toStr(str)
.split(sep, limit)
.map( el => trim ? el.trim() : el )
.filter( el => trim ? !isEmpty(el) : true)
};
const strip = (str, what = null, replace = "") => {
let _str = toStr(str);
let regexp;
if (!what) return _str;
regexp = new RegExp(what, "g");
return _str.replace(regexp, replace);
let _str = toStr(str);
let regexp;
if (!what) return _str
regexp = new RegExp(what, "g");
return _str.replace(regexp, replace)
};

@@ -681,12 +759,13 @@

const matches = (s, pattern, flags = '') => {
let _s = toStr(s);
let patternStr;
if (!(pattern instanceof RegExp)) {
patternStr = pattern ? trim(toStr(pattern)) : '';
if (!patternStr) {
return false;
let _s = toStr(s);
let patternStr;
if (!(pattern instanceof RegExp)) {
patternStr = pattern ? trim(toStr(pattern)) : '';
if (!patternStr) {
return false
}
pattern = new RegExp(patternStr, flags);
}
pattern = new RegExp(patternStr, flags);
}
return pattern.test(_s);
return pattern.test(_s)
};

@@ -699,5 +778,5 @@

const stripBoom = s => {
let _s = toStr(s);
if (_s === '') return _s;
return _s[0] === BYTE_ORDER_MARK ? _s.substring(1) : _s;
let _s = toStr(s);
if (_s === '') return _s
return _s[0] === BYTE_ORDER_MARK ? _s.substring(1) : _s
};

@@ -708,297 +787,366 @@

var f = {
camelCase,
capitalize,
chars: chars$1,
count,
countChars,
countUniqueChars,
countSubstr,
countWords,
countUniqueWords,
dashedName,
decapitalize,
kebab,
lower,
reverse,
shuffle,
snake,
swap,
title,
upper,
words,
wrap,
wrapTag,
escapeHtml,
unescapeHtml,
unique,
uniqueWords,
substring,
first,
last,
truncate,
truncateWithAlign,
slice,
prune,
repeat,
pad,
lpad,
rpad,
insert,
trim,
ltrim,
rtrim,
endsWith,
isAlpha,
isAlphaDigit,
isDigit,
isBlank,
isEmpty,
isLower,
isUpper,
startsWith,
stripTags,
stripTagsAll,
sprintf,
vsprintf,
includes,
split,
strip,
isString,
matches,
append,
prepend,
stripBoom,
shorten
camelCase,
capitalize,
chars: chars$1,
count,
countChars,
countUniqueChars,
countSubstr,
countWords,
countUniqueWords,
dashedName,
decapitalize,
kebab,
lower,
reverse,
shuffle,
snake,
swap,
title,
upper,
words,
wrap,
wrapTag,
escapeHtml,
unescapeHtml,
unique,
uniqueWords,
substring,
first,
last,
truncate,
truncateWithAlign,
slice,
prune,
repeat,
pad,
lpad,
rpad,
insert,
trim,
ltrim,
rtrim,
endsWith,
isAlpha,
isAlphaDigit,
isDigit,
isBlank,
isEmpty,
isLower,
isUpper,
startsWith,
stripTags,
stripTagsAll,
sprintf,
vsprintf,
includes,
split,
strip,
isString,
matches,
append,
prepend,
stripBoom,
shorten
};
class Str {
constructor(v = "", {
mutable = true
} = {}) {
this.value = v.toString();
this.mutable = mutable;
}
[Symbol.toPrimitive](hint) {
if (hint === "number") {
return +this.value;
constructor(v = "", {mutable = true} = {}) {
this.value = v.toString();
this.mutable = mutable;
}
return this.value;
}
get [Symbol.toStringTag]() {
return "Str";
}
val(v) {
if (typeof v === "undefined" || v === null) return this.value;
this.value = v.toString();
return this;
}
get length() {
return this.value.length;
}
immutable(state = true) {
this.mutable = !state;
}
toString() {
return this.value;
}
_result(v) {
if (!this.mutable) {
return str(v);
[Symbol.toPrimitive](hint){
if (hint === "number") {
return +this.value
}
return this.value
}
this.value = v;
return this;
}
camelCase() {
return this._result(f.camelCase(this.value));
}
capitalize(strong) {
return this._result(f.capitalize(this.value, strong));
}
chars(ignore) {
return this._result(f.chars(this.value, ignore));
}
count() {
return f.count(this.value);
}
countChars(ignore) {
return f.countChars(this.value, ignore);
}
countUniqueChars(ignore) {
return f.countUniqueChars(this.value, ignore);
}
countSubstr(sub) {
return f.countSubstr(this.value, sub);
}
countWords(pattern, flags) {
return f.countChars(this.value, pattern, flags);
}
countUniqueWords(pattern, flags) {
return f.countUniqueChars(this.value, pattern, flags);
}
dashedName() {
return this._result(f.dashedName(this.value));
}
decapitalize() {
return this._result(f.decapitalize(this.value));
}
endsWith(str, pos) {
return f.endsWith(this.value, str, pos);
}
escapeHtml() {
return this._result(f.escapeHtml(this.value));
}
first() {
return this._result(f.first(this.value));
}
includes(sub, pos) {
return f.includes(this.value, sub, pos);
}
insert(str, pos) {
return this._result(f.insert(this.value, str, pos));
}
isAlpha() {
return f.isAlpha(this.value);
}
isAlphaDigit() {
return f.isAlphaDigit(this.value);
}
isBlank(strong) {
return f.isBlank(this.value, strong);
}
isDigit() {
return f.isDigit(this.value);
}
isEmpty() {
return f.isEmpty(this.value);
}
isLower() {
return f.isLower(this.value);
}
static isString(v) {
return f.isString(v);
}
isUpper() {
return f.isUpper(this.value);
}
kebab(joinWith) {
return this._result(f.kebab(this.value, joinWith));
}
last(len) {
return this._result(f.last(this.value, len));
}
lower() {
return this._result(f.lower(this.value));
}
matches(pattern, flags) {
return f.matches(this.value, pattern, flags);
}
pad(pad, len) {
return this._result(f.pad(this.value, pad, len));
}
lpad(pad, len) {
return this._result(f.lpad(this.value, pad, len));
}
rpad(pad, len) {
return this._result(f.rpad(this.value, pad, len));
}
prune(len, end) {
return this._result(f.prune(this.value, len, end));
}
repeat(times) {
return this._result(f.repeat(this.value, times));
}
append(str, times) {
return this._result(f.append(this.value, str, times));
}
prepend(str, times) {
return this._result(f.prepend(this.value, str, times));
}
reverse(ignore) {
return this._result(f.reverse(this.value, ignore));
}
shuffle() {
return this._result(f.shuffle(this.value));
}
slice(parts) {
return this._result(f.slice(this.value, parts));
}
snake() {
return this._result(f.snake(this.value));
}
split(sep, limit, trim) {
return this._result(f.split(this.value, sep, limit, trim));
}
sprintf(...args) {
return this._result(f.sprintf(this.value, ...args));
}
vsprintf(...args) {
return this._result(f.vsprintf(this.value, ...args));
}
startsWith(str, pos) {
return f.startsWith(this.value, str, pos);
}
stripBoom() {
return this._result(f.stripBoom(this.value));
}
stripTags(allowed) {
return this._result(f.stripTags(this.value, allowed));
}
stripTagsAll() {
return this._result(f.stripTagsAll(this.value));
}
strip(str, replace) {
return this._result(f.strip(this.value, str, replace));
}
substring(start, len) {
return this._result(f.substring(this.value, start, len));
}
swap() {
return this._result(f.swap(this.value));
}
title(noSplit, sep) {
return this._result(f.title(this.value, noSplit, sep));
}
trim(ws) {
return this._result(f.trim(this.value, ws));
}
ltrim(ws) {
return this._result(f.ltrim(this.value, ws));
}
rtrim(ws) {
return this._result(f.rtrim(this.value, ws));
}
truncate(len, end) {
return this._result(f.truncate(this.value, len, end));
}
truncateWithAlign(len, end) {
return this._result(f.truncateWithAlign(this.value, len, end));
}
unescapeHtml() {
return this._result(f.unescapeHtml(this.value));
}
unique(ignore) {
return this._result(f.unique(this.value, ignore));
}
uniqueWords(pattern, flags) {
return this._result(f.uniqueWords(this.value, pattern, flags));
}
upper() {
return this._result(f.upper(this.value));
}
words(pattern, flags) {
return f.words(this.value, pattern, flags);
}
wrap(before, after) {
return this._result(f.wrap(this.value, before, after));
}
wrapTag(tag) {
return this._result(f.wrapTag(this.value, tag));
}
shorten(l, d) {
return this._result(f.shorten(this.value, l, d));
}
get [Symbol.toStringTag](){return "Str"}
val(v){
if (typeof v === "undefined" || v === null) return this.value
this.value = v.toString();
return this
}
get length(){
return this.value.length
}
immutable(state = true){
this.mutable = !state;
}
toString(){
return this.value
}
_result(v){
if (!this.mutable) {
return str(v)
}
this.value = v;
return this
}
camelCase(){
return this._result(f.camelCase(this.value))
}
capitalize(strong){
return this._result(f.capitalize(this.value, strong))
}
chars(ignore){
return this._result(f.chars(this.value, ignore))
}
count(){
return f.count(this.value)
}
countChars(ignore){
return f.countChars(this.value, ignore)
}
countUniqueChars(ignore){
return f.countUniqueChars(this.value, ignore)
}
countSubstr(sub){
return f.countSubstr(this.value, sub)
}
countWords(pattern, flags){
return f.countChars(this.value, pattern, flags)
}
countUniqueWords(pattern, flags){
return f.countUniqueChars(this.value, pattern, flags)
}
dashedName(){
return this._result(f.dashedName(this.value))
}
decapitalize(){
return this._result(f.decapitalize(this.value))
}
endsWith(str, pos){
return f.endsWith(this.value, str, pos)
}
escapeHtml(){
return this._result(f.escapeHtml(this.value))
}
first(){
return this._result(f.first(this.value))
}
includes(sub, pos){
return f.includes(this.value, sub, pos)
}
insert(str, pos){
return this._result(f.insert(this.value, str, pos))
}
isAlpha(){
return f.isAlpha(this.value)
}
isAlphaDigit(){
return f.isAlphaDigit(this.value)
}
isBlank(strong){
return f.isBlank(this.value, strong)
}
isDigit(){
return f.isDigit(this.value)
}
isEmpty(){
return f.isEmpty(this.value)
}
isLower(){
return f.isLower(this.value)
}
static isString(v){
return f.isString(v)
}
isUpper(){
return f.isUpper(this.value)
}
kebab(joinWith){
return this._result(f.kebab(this.value, joinWith))
}
last(len){
return this._result(f.last(this.value, len))
}
lower(){
return this._result(f.lower(this.value))
}
matches(pattern, flags){
return f.matches(this.value, pattern, flags)
}
pad(pad, len){
return this._result(f.pad(this.value, pad, len))
}
lpad(pad, len){
return this._result(f.lpad(this.value, pad, len))
}
rpad(pad, len){
return this._result(f.rpad(this.value, pad, len))
}
prune(len, end){
return this._result(f.prune(this.value, len, end))
}
repeat(times){
return this._result(f.repeat(this.value, times))
}
append(str, times){
return this._result(f.append(this.value, str, times))
}
prepend(str, times){
return this._result(f.prepend(this.value, str, times))
}
reverse(ignore){
return this._result(f.reverse(this.value, ignore))
}
shuffle(){
return this._result(f.shuffle(this.value))
}
slice(parts){
return this._result(f.slice(this.value, parts))
}
snake(){
return this._result(f.snake(this.value))
}
split(sep, limit, trim){
return this._result(f.split(this.value, sep, limit, trim))
}
sprintf(...args){
return this._result(f.sprintf(this.value, ...args))
}
vsprintf(...args){
return this._result(f.vsprintf(this.value, ...args))
}
startsWith(str, pos){
return f.startsWith(this.value, str, pos)
}
stripBoom(){
return this._result(f.stripBoom(this.value))
}
stripTags(allowed){
return this._result(f.stripTags(this.value, allowed))
}
stripTagsAll(){
return this._result(f.stripTagsAll(this.value))
}
strip(str, replace){
return this._result(f.strip(this.value, str, replace))
}
substring(start, len){
return this._result(f.substring(this.value, start, len))
}
swap(){
return this._result(f.swap(this.value))
}
title(noSplit, sep){
return this._result(f.title(this.value, noSplit, sep))
}
trim(ws){
return this._result(f.trim(this.value, ws))
}
ltrim(ws){
return this._result(f.ltrim(this.value, ws))
}
rtrim(ws){
return this._result(f.rtrim(this.value, ws))
}
truncate(len, end){
return this._result(f.truncate(this.value, len, end))
}
truncateWithAlign(len, end){
return this._result(f.truncateWithAlign(this.value, len, end))
}
unescapeHtml(){
return this._result(f.unescapeHtml(this.value))
}
unique(ignore){
return this._result(f.unique(this.value, ignore))
}
uniqueWords(pattern, flags){
return this._result(f.uniqueWords(this.value, pattern, flags))
}
upper(){
return this._result(f.upper(this.value))
}
words(pattern, flags){
return f.words(this.value, pattern, flags)
}
wrap(before, after){
return this._result(f.wrap(this.value, before, after))
}
wrapTag(tag){
return this._result(f.wrapTag(this.value, tag))
}
shorten(l, d){
return this._result(f.shorten(this.value, l, d))
}
}
Object.assign(Str, f);
const str = v => new Str(v);
export { Str, str };
{
"name": "@olton/string",
"version": "0.4.3",
"version": "0.4.4",
"description": "String is a minimalist JavaScript library for manipulating with strings for node and modern browsers with a comfortable modern API.",

@@ -39,7 +39,2 @@ "main": "dist/string.js",

"devDependencies": {
"@babel/cli": "^7.23.4",
"@babel/core": "^7.23.6",
"@babel/plugin-proposal-throw-expressions": "^7.23.3",
"@babel/preset-env": "^7.23.6",
"@rollup/plugin-babel": "^6.0.4",
"@rollup/plugin-commonjs": "^25.0.7",

@@ -50,5 +45,9 @@ "@rollup/plugin-json": "^6.1.0",

"rollup": "^4.9.0",
"rollup-plugin-terser": "^7.0.2",
"shx": "^0.3.4"
},
"dependencies": {
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-terser": "^0.4.4",
"rollup-plugin-progress": "^1.1.2"
}
}

@@ -1,4 +0,5 @@

import { terser } from 'rollup-plugin-terser'
import { babel } from '@rollup/plugin-babel'
import {nodeResolve} from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import terser from '@rollup/plugin-terser'
import progress from 'rollup-plugin-progress';

@@ -8,2 +9,9 @@ export default [

input: 'src/browser.js',
plugins: [
progress(),
nodeResolve({
browser: true
}),
commonjs(),
],
output: [

@@ -29,2 +37,9 @@ {

input: 'src/index.js',
plugins: [
progress(),
nodeResolve({
browser: true
}),
commonjs(),
],
output: [

@@ -36,7 +51,3 @@ {

],
plugins: [
commonjs(),
babel({ babelHelpers: 'bundled' })
]
}
]
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc