在字符串中大写单词的最佳方法是什么?


当前回答

只要输入字符串中没有重音字母,vsync提供的答案就可以工作。

我不知道原因,但显然\b在regexp匹配也重音字母(在IE8和Chrome上测试),所以像“località”这样的字符串会被错误地大写转换为“LocalitÀ”(à字母被大写,因为regexp认为这是一个单词边界)

一个更通用的函数也适用于重音字母是这样的:

String.prototype.toCapitalize = function()
{ 
   return this.toLowerCase().replace(/^.|\s\S/g, function(a) { return a.toUpperCase(); });
}

你可以这样使用它:

alert( "hello località".toCapitalize() );

其他回答

Jquery或Javascipt没有提供内置方法来实现这一点。

CSS测试转换(text-transform:capitalize;)并不真正大写字符串的数据,而是在屏幕上显示一个大写的渲染。

如果您正在使用普通的香草ajs在数据级别上寻找一种更合法的方法来实现这一点,请使用这个解决方案=>

var capitalizeString = function (word) {    
    word = word.toLowerCase();
    if (word.indexOf(" ") != -1) { // passed param contains 1 + words
        word = word.replace(/\s/g, "--");
        var result = $.camelCase("-" + word);
        return result.replace(/-/g, " ");
    } else {
    return $.camelCase("-" + word);
    }
}

Ivo的答案很好,但我更喜欢不匹配\w,因为没有必要大写0-9和A-Z。我们可以忽略这些,只匹配a-z。

'your string'.replace(/\b[a-z]/g, match => match.toUpperCase())
// => 'Your String'

这是相同的输出,但我认为在自文档代码方面更清楚。

用这个:

String.prototype.toTitleCase = function() { 返回this.charAt(0).toUpperCase() + this.slice(1); } 让STR = 'text'; document.querySelector(#演示)。innerText = str.toTitleCase(); <div class = "app"> <p id = "demo"></p> . < / div >

你可以使用以下方法将字符串中的单词大写:

function capitalizeAll(str){

    var partes = str.split(' ');

    var nuevoStr = ""; 

    for(i=0; i<partes.length; i++){
    nuevoStr += " "+partes[i].toLowerCase().replace(/\b\w/g, l => l.toUpperCase()).trim(); 
    }    

    return nuevoStr;

}

我的解决方案:

String.prototype.toCapital = function () {
    return this.toLowerCase().split(' ').map(function (i) {
        if (i.length > 2) {
            return i.charAt(0).toUpperCase() + i.substr(1);
        }

        return i;
    }).join(' ');
};

例子:

'álL riGht'.toCapital();
// Returns 'Áll Right'