Arslan Farooq Arslan Farooq - 1 month ago 6
jQuery Question

Convert Text to Title Case Recursively Using jQuery

I'm trying to change all instance of text in an HTML document to title case. The jQuery code here works for only single occurrence.

How can this be made to work recursively? :



var ele = $('h3');
ele.text(toProperCase(ele.text()));

function toProperCase(str)
{
var noCaps = ['of','a','the','and','an','am','or','nor','but','is','if','then',
'else','when','at','from','by','on','off','for','in','out','to','into','with'];
return str.replace(/\w\S*/g, function(txt, offset){
if(offset != 0 && noCaps.indexOf(txt.toLowerCase()) != -1){
return txt.toLowerCase();
}
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h3>THE QUICK BROWN FOX IS ABOUT TO JUMP OVER THE FENCE</h3>

<h3 style="color: red;">HELLO THERE</h3>




Answer

.text() only applies to the first element, use a loop

var ele = $('h3'); 
ele.each(function() {
    $(this).text(toProperCase($(this).text())); 
}

var ele = $('h3'); 
ele.each(function() { 
    $(this).text(toProperCase($(this).text())); 
});

function toProperCase(str)
{
    var noCaps = ['of','a','the','and','an','am','or','nor','but','is','if','then', 
'else','when','at','from','by','on','off','for','in','out','to','into','with'];
    return str.replace(/\w\S*/g, function(txt, offset){
        if(offset != 0 && noCaps.indexOf(txt.toLowerCase()) != -1){
            return txt.toLowerCase();    
        }
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h3>THE QUICK BROWN FOX IS ABOUT TO JUMP OVER THE FENCE</h3>

<h3 style="color: red;">HELLO THERE</h3>