JSFiddle - React, Tailwind, and code Playground
by rigor789
JavaScript
const CLASS_RE = /\sclass=['"](.+)['"]/i
// get classnames from built css in order
const css = [
'bg-blue',
'text-red',
'px-4',
'py-2',
'mt-2'
]
function sortClasses(text) {
const res = text.match(CLASS_RE)
const classes = res[1].split(/\s+/)
classes.sort((a, b) => {
return css.indexOf(a) - css.indexOf(b)
})
return text.replace(res[1], classes.join(' '))
}
const tests = [{
input: '<foo class="text-red mt-2 bg-blue py-2 px-4">',
expected: '<foo class="bg-blue text-red px-4 py-2 mt-2">'
},
{
input: '<foo class="bg-blue py-2 px-4 text-red mt-2">',
expected: '<foo class="bg-blue text-red px-4 py-2 mt-2">'
},
{
input: '<foo class="bg-blue text-red">',
expected: '<foo class="bg-blue text-red">'
},
]
let fails = 0,
oks = 0;
tests.forEach(testCase => {
const result = sortClasses(testCase.input)
if (result !== testCase.expected) {
fails++
console.log(`Test case failed
Input: %c${testCase.input}
%c
Expected: %c${testCase.expected}%c
Actual: %c${result}`,
'color: blue', 'color: black', 'color: green', 'color: black', 'color: red')
} else {
oks++
}
})
console.log(`${tests.length} tests. %c${oks} OK. %c${fails} failed.`, 'color: green', 'color: red')