@trapcode/codebase
Version:
For TrapCode
134 lines (119 loc) • 3.66 kB
JavaScript
let StringHelper;
import DataHelper from "./data";
export default StringHelper = class StringHelper extends DataHelper {
splitInFours(theString) {
let theStringArr;
theStringArr = theString.split('');
$.each(theStringArr, function (key, val) {
if ((key + 1) % 4 === 0 && theStringArr.hasOwnProperty(key + 1)) {
return theStringArr[key] = val + "-";
}
});
return theStringArr.join('');
}
randomStr(length = 10) {
let i, possible, text;
text = '';
possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
i = 0;
while (i < length) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
i++;
}
return text;
}
slugify(str) {
let from, i, l, to;
str = str.replace(/^\s+|\s+$/g, '');
// trim
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
from = 'àáäâèéëêìíïîòóöôùúüûñç·/_,:;';
to = 'aaaaeeeeiiiioooouuuunc------';
i = 0;
l = from.length;
while (i < l) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
i++;
}
str = str.replace(/[^a-z0-9 -]/g, '').replace(/\s+/g, '-').replace(/-+/g, '-');
// collapse dashes
return str;
}
ucfirst(str) {
if (str.length > 0) {
str = str.replace(str[0], str[0].toUpperCase());
}
return str;
}
removeLastChar(str, char, depth = 1) {
str = str.trim();
if (str.substring(str.length - depth) === char) {
str = str.substring(0, str.length - depth);
}
return str;
}
stripSlashes(str) {
return (str + '').replace(/\\(.?)/g, function (s, n1) {
switch (n1) {
case '\\':
return '\\';
case '0':
return '\u0000';
case '':
return '';
default:
return n1;
}
});
}
strLimit(str, end = 100, continuation = '....') {
if (str.length > end) {
return str.substring(0, end).trim() + continuation;
} else {
return str;
}
}
numberToString(n, d = 2) {
let $round, abs, base, floor, log, pow, suffix;
pow = Math.pow;
floor = Math.floor;
abs = Math.abs;
log = Math.log;
$round = function (n, precision) {
let prec;
prec = 10 ** precision;
return Math.round(n * prec) / prec;
};
base = floor(log(abs(n)) / log(1000));
suffix = 'kmb'[base - 1];
if (suffix) {
return $round(n / pow(1000, base), d) + suffix;
} else {
return '' + n;
}
}
numberFormat(number, remove = 3) {
let stringText;
stringText = (parseFloat(number)).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
if (stringText.indexOf('.')) {
return stringText.substr(0, stringText.length - remove);
} else {
return stringText;
}
}
stringToBool(str) {
let int;
int = parseInt(str);
if (typeof int === 'number' && int > 0) {
return true;
}
return false;
}
decodeUnicode(str) {
return decodeURIComponent(JSON.parse('"' + str + '"'));
}
prefixIdWith(prefix = 'prefix', id = 0) {
return prefix + '_' + id;
}
};