SELECTED ANSWER
replied on October 29, 2024
Here is a more reliable method. It first checks for spaces and splits into individual words and then processes each word. If the word has a hyphen, it splits on the hyphen and processes the 2 parts individually, otherwise it just processes the word.
$(document).ready(function () {
$('.toTitleCase input').change(function() {
// get input as lower case
var sInput = $(this).val().toLowerCase();
// split on space
var words = sInput.split(" ");
// process each individual word
for (let i = 0; i < words.length; i++) {
// process words with hyphen
if (words[i].indexOf('-') > -1) {
// text up to and including hyphen
var w1 = words[i].slice(0, words[i].indexOf('-') + 1);
// process if not blank
if (w1) {
w1 = procText(w1);
}
// text after the hyphen
var w2 = words[i].slice(words[i].indexOf('-') + 1);
// process if not blank
if (w2) {
w2 = procText(w2);
}
// put processed text back together
words[i] = w1 + w2;
} else {
// process unhyphenated words
words[i] = procText(words[i]);
}
}
// put processed text back together
sInput = words.join(" ");
// Set the field value
$(this).val(sInput);
});
function procText(txt) {
// variable to track if we split the word
var addSpace = false;
// check if startes with mc
if (txt.startsWith("mc")){
// set variable that we split the word
addSpace = true;
// add space after first 2 characters
txt = txt.slice(0, 2) + " " + txt.slice(2);
}
// check if startes with o'
if (txt.startsWith("o'")){
// set variable that we split the word
addSpace = true;
// add space after first 2 characters
txt = txt.slice(0, 2) + " " + txt.slice(2);
}
// split on space
var words = txt.split(" ");
// process each part
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
// update text with processed data
txt = words.join(" ");
// check if need to remove space
if (addSpace) {
// remove space
txt = txt.replace(/ /, '');
}
// returned processed data
return txt;
}
});