2016-10-10 03:43:44 +02:00
|
|
|
'use strict';
|
2017-04-20 03:09:25 +02:00
|
|
|
|
|
|
|
function preserveCamelCase(str) {
|
2017-08-14 05:01:11 +02:00
|
|
|
let isLastCharLower = false;
|
|
|
|
let isLastCharUpper = false;
|
|
|
|
let isLastLastCharUpper = false;
|
2017-04-20 03:09:25 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
for (let i = 0; i < str.length; i++) {
|
|
|
|
const c = str[i];
|
2017-04-20 03:09:25 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) {
|
2017-04-20 03:09:25 +02:00
|
|
|
str = str.substr(0, i) + '-' + str.substr(i);
|
|
|
|
isLastCharLower = false;
|
2017-08-14 05:01:11 +02:00
|
|
|
isLastLastCharUpper = isLastCharUpper;
|
|
|
|
isLastCharUpper = true;
|
2017-04-20 03:09:25 +02:00
|
|
|
i++;
|
2017-08-14 05:01:11 +02:00
|
|
|
} else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(c) && c.toLowerCase() === c) {
|
|
|
|
str = str.substr(0, i - 1) + '-' + str.substr(i - 1);
|
|
|
|
isLastLastCharUpper = isLastCharUpper;
|
|
|
|
isLastCharUpper = false;
|
|
|
|
isLastCharLower = true;
|
2017-04-20 03:09:25 +02:00
|
|
|
} else {
|
2017-08-14 05:01:11 +02:00
|
|
|
isLastCharLower = c.toLowerCase() === c;
|
|
|
|
isLastLastCharUpper = isLastCharUpper;
|
|
|
|
isLastCharUpper = c.toUpperCase() === c;
|
2017-04-20 03:09:25 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return str;
|
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
module.exports = function (str) {
|
|
|
|
if (arguments.length > 1) {
|
|
|
|
str = Array.from(arguments)
|
|
|
|
.map(x => x.trim())
|
|
|
|
.filter(x => x.length)
|
|
|
|
.join('-');
|
|
|
|
} else {
|
|
|
|
str = str.trim();
|
|
|
|
}
|
2016-10-10 03:43:44 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
if (str.length === 0) {
|
2016-10-10 03:43:44 +02:00
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
2017-04-20 03:09:25 +02:00
|
|
|
if (str.length === 1) {
|
|
|
|
return str.toLowerCase();
|
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
if (/^[a-z0-9]+$/.test(str)) {
|
2017-04-20 03:09:25 +02:00
|
|
|
return str;
|
2016-10-10 03:43:44 +02:00
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
const hasUpperCase = str !== str.toLowerCase();
|
|
|
|
|
|
|
|
if (hasUpperCase) {
|
|
|
|
str = preserveCamelCase(str);
|
|
|
|
}
|
2017-04-20 03:09:25 +02:00
|
|
|
|
2016-10-10 03:43:44 +02:00
|
|
|
return str
|
2017-08-14 05:01:11 +02:00
|
|
|
.replace(/^[_.\- ]+/, '')
|
|
|
|
.toLowerCase()
|
|
|
|
.replace(/[_.\- ]+(\w|$)/g, (m, p1) => p1.toUpperCase());
|
2016-10-10 03:43:44 +02:00
|
|
|
};
|