@gitlab/ui
Version:
GitLab UI Components
48 lines (35 loc) • 2.08 kB
JavaScript
import { RX_HYPHENATE, RX_UNDERSCORE, RX_LOWER_UPPER, RX_START_SPACE_WORD, RX_REGEXP_REPLACE, RX_TRIM_LEFT, RX_TRIM_RIGHT } from '../constants/regex';
import { isString, isUndefinedOrNull, isArray, isPlainObject } from './inspect';
// String utilities
// --- Utilities ---
// Converts PascalCase or camelCase to kebab-case
const kebabCase = str => {
return str.replace(RX_HYPHENATE, '-$1').toLowerCase();
};
// Converts a string, including strings in camelCase or snake_case, into Start Case
// It keeps original single quote and hyphen in the word
// https://github.com/UrbanCompass/to-start-case
const startCase = str => str.replace(RX_UNDERSCORE, ' ').replace(RX_LOWER_UPPER, (str, $1, $2) => $1 + ' ' + $2).replace(RX_START_SPACE_WORD, (str, $1, $2) => $1 + $2.toUpperCase());
// Uppercases the first letter of a string and returns a new string
const upperFirst = str => {
str = isString(str) ? str.trim() : String(str);
return str.charAt(0).toUpperCase() + str.slice(1);
};
// Escape characters to be used in building a regular expression
const escapeRegExp = str => str.replace(RX_REGEXP_REPLACE, '\\$&');
// Convert a value to a string that can be rendered
// `undefined`/`null` will be converted to `''`
// Plain objects and arrays will be JSON stringified
const toString = function (val) {
let spaces = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
return isUndefinedOrNull(val) ? '' : isArray(val) || isPlainObject(val) && val.toString === Object.prototype.toString ? JSON.stringify(val, null, spaces) : String(val);
};
// Remove leading white space from a string
const trimLeft = str => toString(str).replace(RX_TRIM_LEFT, '');
// Remove Trailing white space from a string
const trimRight = str => toString(str).replace(RX_TRIM_RIGHT, '');
// Remove leading and trailing white space from a string
const trim = str => toString(str).trim();
// Lower case a string
const lowerCase = str => toString(str).toLowerCase();
export { escapeRegExp, kebabCase, lowerCase, startCase, toString, trim, trimLeft, trimRight, upperFirst };