Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify the first letter of each word in a string using javascript while keeping inner HTML intact?

The following code looks at any element with the "title-case" class and modifies the first letter of each word to be slightly bigger IF it is an uppercase letter. Here is the code:

$(document).ready(function(){
    $('.title-case').each(function(){
        $(this).html( capitalize_first_letter( $(this).html() ) );
    });
});

function capitalize_first_letter( str ) {
    var words = str.split(' ');
    var html = '';
    $.each(words, function() {
        var first_letter = this.substring(0,1);
        html += ( first_letter == first_letter.toUpperCase() ? '<span class="first-letter">'+first_letter+'</span>' : first_letter )+this.substring(1) + ' ';
    });
    return html;
}

You can see it run here: http://jsfiddle.net/82Ebt/

It works for the most part but as you can see from the example it will break the inner HTML nodes. I'm actually at a loss as to how to tackle this and could use some ideas. I figured maybe manipulating just the .text() instead of .html() but that strips out the HTML outright.

Edit: I would like to point out that the reason I use javascript is because I would like every word in the string to have it's first letter bigger IF it is capitalized. The :first-letter pseudo-class only affects the first word.

Thanks :)

like image 753
Gazillion Avatar asked Jan 16 '23 07:01

Gazillion


1 Answers

This seems to work, at least in modern browsers -- use .html() with a callback and .replace() with a regex to detect only initial capital letters:

$('.title-case').html(function(i,el) {
    return el.replace(/\b([A-Z])/g, "<span class=\"first-letter\">$1</span>");
});
​

http://jsfiddle.net/mblase75/82Ebt/4/

like image 127
Blazemonger Avatar answered Jan 18 '23 22:01

Blazemonger