forked from sindresorhus/slugify
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
84 lines (66 loc) · 2.16 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict';
var escapeStringRegexp = require('escape-string-regexp');
var transliterate = require('@sindresorhus/transliterate');
var builtinOverridableReplacements = require('./overridable-replacements');
if (!Object.keys) Object.keys = function(o) {
if (o !== Object(o))
throw new TypeError('Object.keys called on a non-object');
var k=[],p;
for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
return k;
}
function objAssign(objs) {
return objs.reduce(function (r, o) {
try {
var d = r;
Object.keys(o).forEach(function (k) { d[k] = o[k]; });
return d;
} catch { return r; }
}, {});
};
function decamelize(string) {
return string
// Separate capitalized words.
.replace(/([A-Z]{2,})([a-z\d]+)/g, '$1 $2')
.replace(/([a-z\d]+)([A-Z]{2,})/g, '$1 $2')
.replace(/([a-z\d])([A-Z])/g, '$1 $2')
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1 $2');
};
function removeMootSeparators(string, separator) {
var escapedSeparator = escapeStringRegexp(separator);
return string
.replace(new RegExp(`${escapedSeparator}{2,}`, 'g'), separator)
.replace(new RegExp(`^${escapedSeparator}|${escapedSeparator}$`, 'g'), '');
};
module.exports = function (initString, initOptions) {
if (typeof initString !== 'string') {
throw new TypeError(`Expected a string, got \`${typeof initString}\``);
}
var str = initString;
var options = initOptions || {};
options = objAssign([{
separator: '-',
lowercase: true,
decamelize: true,
customReplacements: [],
preserveLeadingUnderscore: false,
}, options]);
var shouldPrependUnderscore = options.preserveLeadingUnderscore && str.startsWith('_');
var customReplacements = [].concat(builtinOverridableReplacements).concat(options.customReplacements).filter(Boolean);
str = transliterate(str, {customReplacements});
if (options.decamelize) {
str = decamelize(str);
}
var patternSlug = /[^a-zA-Z\d]+/g;
if (options.lowercase) {
str = str.toLowerCase();
patternSlug = /[^a-z\d]+/g;
}
str = str.replace(patternSlug, options.separator);
str = str.replace(/\\/g, '');
str = removeMootSeparators(str, options.separator);
if (shouldPrependUnderscore) {
str = `_${str}`;
}
return str;
};