@apicart/js-utils
Version:
A small set of useful utilities for easier development
53 lines (39 loc) • 1.14 kB
text/typescript
import { Loops } from '.';
class Strings {
public firstToUpper(string: string): string
{
return string.charAt(0).toUpperCase() + string.slice(1);
}
public generateHash(length: number, characters = 'abcdefghijklmnopqrstuvwxyz0123456789'): string
{
let hash = '';
while (length--) {
hash += characters.charAt(Math.floor(Math.random() * characters.length));
}
return hash;
}
public sprintf(content: string, parameters: any): string
{
Loops.forEach(parameters, (value: any, key: string|number): void => {
if (!['number', 'string'].includes(typeof value)) {
return;
}
content = content.replace(new RegExp('%' + key + '%', 'g'), value);
});
return content;
}
public stripHtml(content: string): string
{
const el = document.createElement('div');
el.innerHTML = content;
return el.textContent || el.innerText || '';
}
public truncate(content: string, length: number, separator = ' ', ending = '...'): string
{
if (content.length <= length) {
return content;
}
return content.substr(0, content.lastIndexOf(separator, length - 3)) + ending;
}
}
export default new Strings();