UNPKG

@oxog/string

Version:

Comprehensive string manipulation utilities with zero dependencies

94 lines (93 loc) 2.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.trim = trim; exports.trimStart = trimStart; exports.trimEnd = trimEnd; exports.removeExtraSpaces = removeExtraSpaces; exports.normalizeWhitespace = normalizeWhitespace; exports.removeNonPrintable = removeNonPrintable; exports.stripHtml = stripHtml; exports.stripAnsi = stripAnsi; exports.removeAccents = removeAccents; const unicode_1 = require("../utils/unicode"); function trim(str, chars) { if (!str || typeof str !== 'string') return ''; if (!chars) { return str.trim(); } const pattern = new RegExp(`^[${escapeRegExp(chars)}]+|[${escapeRegExp(chars)}]+$`, 'g'); return str.replace(pattern, ''); } function trimStart(str, chars) { if (!str || typeof str !== 'string') return ''; if (!chars) { return str.trimStart(); } const pattern = new RegExp(`^[${escapeRegExp(chars)}]+`, 'g'); return str.replace(pattern, ''); } function trimEnd(str, chars) { if (!str || typeof str !== 'string') return ''; if (!chars) { return str.trimEnd(); } const pattern = new RegExp(`[${escapeRegExp(chars)}]+$`, 'g'); return str.replace(pattern, ''); } function removeExtraSpaces(str) { if (!str || typeof str !== 'string') return ''; return str.replace(/\s+/g, ' ').trim(); } function normalizeWhitespace(str) { if (!str || typeof str !== 'string') return ''; return str .replace(/[\t\n\r\f\v]/g, ' ') .replace(/\s+/g, ' ') .trim(); } function removeNonPrintable(str) { if (!str || typeof str !== 'string') return ''; return str.replace(/[\x00-\x1F\x7F-\x9F]/g, ''); } function stripHtml(str) { if (!str || typeof str !== 'string') return ''; return str .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '') .replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '') .replace(/<[^>]*>/g, '') .replace(/&[#\w]+;/g, (entity) => { const htmlEntities = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&apos;': "'", '&nbsp;': ' ', '&copy;': '©', '&reg;': '®', '&trade;': '™' }; return htmlEntities[entity] || entity; }); } function stripAnsi(str) { if (!str || typeof str !== 'string') return ''; const ansiRegex = /\x1b\[[0-9;]*m/g; return str.replace(ansiRegex, ''); } function removeAccents(str) { if (!str || typeof str !== 'string') return ''; return (0, unicode_1.removeAccents)(str); } function escapeRegExp(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }