Most efficient way to turn all caps into title case with JS or JQuery?
You could match consecutive word characters, and use a replacer function to replace with the first character (as-is), followed by the rest with toLowerCase()
called on them:
const text = 'THIS IS MY STRING WHY AM I YELLLING?';
const output = text.replace(
/(\w)(\w*)/g,
(_, firstChar, rest) => firstChar + rest.toLowerCase()
);
console.log(output);
Another possible solution could be using the regular expression /./g
in String.replace() and check on the replacement function if the previous character, of the current matched one, is a letter
and the offset
of this one is not zero
, to decide whether to replace the character by the lower-case
or upper-case
version.
let str = "THIS IS MY STRING WHY AM I YELLLING. WASHINGTON D.C?";
let out = str.replace(/./g, (m, offset, str) =>
{
return (offset !== 0 && /\w/.test(str[offset-1])) ? m.toLowerCase() : m.toUpperCase();
});
console.log(out);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}