Convert string to title case with JavaScript

后端 未结 30 2838
夕颜
夕颜 2020-11-21 06:40

Is there a simple way to convert a string to title case? E.g. john smith becomes John Smith. I\'m not looking for something complicated like John R

30条回答
  •  情书的邮戳
    2020-11-21 07:30

    Here is my function that is taking care of accented characters (important for french !) and that can switch on/off the handling of lowers exceptions. Hope that helps.

    String.prototype.titlecase = function(lang, withLowers = false) {
        var i, string, lowers, uppers;
    
        string = this.replace(/([^\s:\-'])([^\s:\-']*)/g, function(txt) {
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        }).replace(/Mc(.)/g, function(match, next) {
            return 'Mc' + next.toUpperCase();
        });
    
        if (withLowers) {
            if (lang == 'EN') {
                lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];
            }
            else {
                lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];
            }
            for (i = 0; i < lowers.length; i++) {
                string = string.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) {
                    return txt.toLowerCase();
                });
            }
        }
    
        uppers = ['Id', 'R&d'];
        for (i = 0; i < uppers.length; i++) {
            string = string.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase());
        }
    
        return string;
    }
    

提交回复
热议问题