Make sanitizeSlug
immutable.
Thanks @erquhart!
This commit is contained in:
parent
72492749d9
commit
8fb326ff2b
@ -1,6 +1,6 @@
|
||||
import url from 'url';
|
||||
import sanitizeFilename from 'sanitize-filename';
|
||||
import { isString, escapeRegExp } from 'lodash';
|
||||
import { isString, escapeRegExp, flow, partialRight } from 'lodash';
|
||||
|
||||
function getUrl(url, direct) {
|
||||
return `${ direct ? '/#' : '' }${ url }`;
|
||||
@ -33,18 +33,22 @@ export function sanitizeIRI(str, { replacement }) {
|
||||
export function sanitizeSlug(str, { replacement = '-' }) {
|
||||
if (!isString(str)) throw "`sanitizeSlug` only accepts strings as input.";
|
||||
if (!isString(replacement)) throw "the `sanitizeSlug` replacement character must be a string.";
|
||||
let slug = str;
|
||||
|
||||
|
||||
// Sanitize as IRI (i18n URI) and as filename.
|
||||
slug = sanitizeIRI(slug, {replacement});
|
||||
slug = sanitizeFilename(slug, {replacement});
|
||||
|
||||
const sanitize = flow([
|
||||
partialRight(sanitizeIRI, { replacement }),
|
||||
partialRight(sanitizeFilename, { replacement }),
|
||||
]);
|
||||
const sanitizedSlug = sanitize(str);
|
||||
|
||||
// Remove any doubled or trailing replacement characters (that were added in the sanitizers).
|
||||
const doubleReplacement = new RegExp('(?:' + escapeRegExp(replacement) + ')+', 'g');
|
||||
const trailingReplacment = new RegExp(escapeRegExp(replacement) + '$')
|
||||
slug = slug.replace(doubleReplacement, '-').replace(trailingReplacment, '');
|
||||
const trailingReplacment = new RegExp(escapeRegExp(replacement) + '$');
|
||||
const normalizedSlug = sanitizedSlug
|
||||
.replace(doubleReplacement, '-')
|
||||
.replace(trailingReplacment, '');
|
||||
|
||||
return slug;
|
||||
return normalizedSlug;
|
||||
}
|
||||
|
||||
export function urlize(string) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user