strapi/packages/core/utils/lib/string-formatting.js

50 lines
1.3 KiB
JavaScript
Raw Normal View History

'use strict';
const _ = require('lodash');
const slugify = require('@sindresorhus/slugify');
const nameToSlug = (name, options = { separator: '-' }) => slugify(name, options);
const nameToCollectionName = name => slugify(name, { separator: '_' });
2021-08-17 19:10:29 +02:00
const getCommonBeginning = (...strings) =>
_.takeWhile(strings[0], (char, index) => strings.every(string => string[index] === char)).join(
''
);
const getCommonPath = (...paths) => {
const [segments, ...otherSegments] = paths.map(it => _.split(it, '/'));
return _.join(
2021-08-17 19:10:29 +02:00
_.takeWhile(segments, (str, index) => otherSegments.every(it => it[index] === str)),
'/'
);
};
const escapeQuery = (query, charsToEscape, escapeChar = '\\') => {
return query
.split('')
.reduce(
(escapedQuery, char) =>
charsToEscape.includes(char)
? `${escapedQuery}${escapeChar}${char}`
: `${escapedQuery}${char}`,
''
);
};
const stringIncludes = (arr, val) => arr.map(String).includes(String(val));
const stringEquals = (a, b) => String(a) === String(b);
2021-08-20 15:23:02 +02:00
const isCamelCase = value => /^[a-z][a-zA-Z0-9]+$/.test(value);
const isKebabCase = value => /^([a-z][a-z0-9]*)(-[a-z0-9]+)*$/.test(value);
module.exports = {
nameToSlug,
nameToCollectionName,
getCommonBeginning,
getCommonPath,
escapeQuery,
stringIncludes,
stringEquals,
2021-08-20 15:23:02 +02:00
isCamelCase,
isKebabCase,
};