@oxog/string
Version:
Comprehensive string manipulation utilities with zero dependencies
49 lines (48 loc) • 1.49 kB
JavaScript
import { getGraphemes, getCodePoints } from '../utils/unicode';
import { boyerMooreSearch } from '../utils/algorithms';
export function contains(str, search, caseSensitive = true) {
if (!caseSensitive) {
return str.toLowerCase().includes(search.toLowerCase());
}
return str.includes(search);
}
export function count(str, search) {
if (!search)
return 0;
let count = 0;
let position = 0;
while ((position = str.indexOf(search, position)) !== -1) {
count++;
position += search.length;
}
return count;
}
export function indexOfAll(str, search) {
if (!search)
return [];
return boyerMooreSearch(str, search);
}
export function words(str, locale) {
if (locale && typeof Intl !== 'undefined' && 'Segmenter' in Intl) {
try {
const segmenter = new Intl.Segmenter(locale, { granularity: 'word' });
return Array.from(segmenter.segment(str))
.filter((segment) => segment.isWordLike)
.map((segment) => segment.segment);
}
catch (_a) {
// Fall back to default implementation if locale is invalid
}
}
// Use a more inclusive regex that handles Unicode characters
return str.match(/[\p{L}\p{N}]+/gu) || [];
}
export function chars(str) {
return getGraphemes(str);
}
export function codePoints(str) {
return getCodePoints(str);
}
export function graphemes(str) {
return getGraphemes(str);
}