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