string-playground
Version:
String utility functions for clean and consistent text handling in JavaScript.
65 lines • 3.09 kB
JavaScript
// Converts a string to a URL-friendly slug by replacing spaces and underscores with hyphens and removing non-alphanumeric characters except hyphens.
export var toSlug = function (str) {
return str
.toLowerCase()
.trim()
.replace(/[\s_]+/g, '-') // Replace spaces and underscores with hyphens
.replace(/[^\w-]+/g, ''); // Remove non-alphanumeric characters except hyphens
};
// Capitalizes the first character of the string after trimming any leading or trailing spaces.
export var capitalizeFirstWord = function (str) {
return str
.trim()
.replace(/^\w/, function (c) { return c.toUpperCase(); }); // Capitalize the first character
};
// Capitalizes the first character of each word in the string after trimming spaces.
export var capitalizeWords = function (str) {
return str
.trim()
.replace(/\b\w/g, function (c) { return c.toUpperCase(); }); // Capitalize the first character of each word
};
// Converts a string to camelCase by removing spaces and capitalizing the first letter of each word except the first word.
export var camelCase = function (str) {
return str
.toLowerCase()
.trim()
.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) {
return index === 0 ? match.toLowerCase() : match.toUpperCase();
})
.replace(/\s+/g, ''); // Remove spaces
};
// Counts the number of words in a string by splitting it on spaces and filtering out empty entries.
export var countWords = function (str) {
return str
.trim()
.split(/\s+/).filter(Boolean).length; // Split by spaces and count non-empty words
};
// Removes all numeric characters from the string.
export var removeNumbers = function (str) {
return str.replace(/\d+/g, ''); // Remove all digits
};
// Removes all non-letter characters from the string, except spaces.
export var onlyLetters = function (str) {
return str.replace(/[^a-zA-Z\s]/g, ''); // Remove non-letter characters except spaces
};
// Removes extra spaces from the string, leaving only single spaces between words.
export var removeExtraSpaces = function (str) {
return str
.trim()
.replace(/\s+/g, ' '); // Replace multiple spaces with a single space
};
// Converts a string to dot.case by replacing spaces with dots and converting to lowercase.
export var dotCase = function (str) {
return str
.toLowerCase()
.trim()
.replace(/\s+/g, '.'); // Replace spaces with dots
};
export var removeWords = function (str, blacklist, caseSensitive) {
return blacklist.reduce(function (acc, word) {
var escapedWord = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // Escape special characters in the word
var regex = new RegExp("\\s*".concat(escapedWord, "\\s*"), "g".concat(caseSensitive ? '' : 'i')); // Match the word with optional spaces around it
return acc.replace(regex, ' ').trim(); // Replace with a single space and trim the result
}, str).replace(/\s+/g, ' '); // Ensure no extra spaces remain
};
//# sourceMappingURL=index.js.map