JSFiddle - React, Tailwind, and code Playground
by Mike McCaughan
HTML
<div id="pre">ThereAreALotOfWordsInThisWordPlus1234Numbers</div>
<div id="post"></div>
<div id="post-re"></div>
JavaScript
var classNameSubstitutions = {
'A': '-a',
'B': '-b',
'C': '-c',
'D': '-d',
'E': '-e',
'F': '-f',
'G': '-g',
'H': '-h',
'I': '-i',
'J': '-j',
'K': '-k',
'L': '-l',
'M': '-m',
'N': '-n',
'O': '-o',
'P': '-p',
'Q': '-q',
'R': '-r',
'S': '-s',
'T': '-t',
'U': '-u',
'V': '-v',
'W': '-w',
'X': '-x',
'Y': '-y',
'Z': '-z',
'0': '-0',
'1': '-1',
'2': '-2',
'3': '-3',
'4': '-4',
'5': '-5',
'6': '-6',
'7': '-7',
'8': '-8',
'9': '-9'
};
function getCssClassName(value) {
var first = value[0].toLowerCase(),
rest = value.substring(1),
result = '';
for (var i = 0, z = rest.length; i < z; i++) {
var char = rest[i],
subs = classNameSubstitutions[char];
if (subs && subs.length) {
result += subs;
} else {
result += char;
}
}
return first + result;
}
var capitalNumberRe = /[^-]([0-9A-Z])/;
function parseCssClassName(value) {
var matches = capitalNumberRe.exec(value);
do {
console.log(matches.index);
value = value.replace(matches[1], (matches.index === 0 ? '' : '-') + matches[1].toLowerCase());
} while (matches = capitalNumberRe.exec(value));
return value[0] === '-' ? value.substring(1) : value;
}
var val = document.getElementById('pre').innerText;
document.getElementById('post').innerText = getCssClassName(val);
document.getElementById('post-re').innerText = parseCssClassName(val);