简体   繁体   中英

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 :)

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/

You could use CSS: It only affects first word

http://jsfiddle.net/82Ebt/1/

.title-case {
    text-transform: uppercase;
}
.title-case:first-letter {
    font-size: 115%;
}

Works in IE7+ (i don't have IE6) and i'd be surprised if any of the other common browsers didn't support it

Try this method: Its working for me.

    function capitalise(text) {

    var split = text.split(" "),
    res = [],
    i,
    len,
    component;

    $(split).each(function (index, element) {

        component = (element + "").trim();
        var first = component.substring(0, 1).toUpperCase();
        var remain = component.substring(1).toLowerCase();

        res.push(first);
        res.push(remain);
        res.push(" "); 

    });

    return res.join("");
}

Try like this:

 $('.title-case').children().andSelf().each(function(){
     $(this).html( capitalize_first_letter( $(this).text() ) );
 });

 function capitalize_first_letter( str ) {    
    return str.replace(/\b[A-Z]/g,'<span class="first-letter">$&</span>');    
 }​

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM