diff --git a/core/extras/string.js b/core/extras/string.js index ebd42ba65..6861f45f1 100644 --- a/core/extras/string.js +++ b/core/extras/string.js @@ -149,6 +149,33 @@ if (!String.prototype.toCamelCase) { String.prototype.toLowerCamelCase.cache = Object.create(null); } +if (typeof String.prototype.toKebabCase !== "function") { + const kebabCaseCache = Object.create(null); + + /** + * Converts a string to kebab-case. + * @function external:String#toKebabCase + * @returns {string} The string converted to kebab-case. + * @example + * "Hello World".toKebabCase(); // "hello-world" + */ + Object.defineProperty(String.prototype, "toKebabCase", { + value: function toKebabCase() { + if (!this) return ""; + if (kebabCaseCache[this]) return kebabCaseCache[this]; + + kebabCaseCache[this] = this.trim() + .split(/[_\s-]+|(?<=[a-z])(?=[A-Z])/) + .map((word) => word.toLowerCase()) + .join("-"); + + return kebabCaseCache[this]; + }, + writable: true, + configurable: true, + }); +} + if(typeof String.prototype.removeSuffix !== "function") { Object.defineProperty(String.prototype, "removeSuffix", { value: function (suffix) { @@ -290,7 +317,7 @@ if(typeof String.prototype.substringWithinRange !== "function") { value: function substringWithinRange (aRange) { /* substring: indexStart: The index of the first character to include in the returned substring. - + indexEnd: The index of the first character to exclude from the returned substring. */ return this.substring(aRange.includesBegin ? aRange.begin : (aRange.begin + 1), aRange.includesEnd ? (aRange.end + 1) : aRange.end)