如何将每个单词的首字母大写,就像一个2个单词的城市?

2022-08-30 00:17:23

我的JS在城市有一个词时做得很好:

  • cHIcaGO ==> 芝加哥

但是当它是

  • 圣地亚哥==>圣地亚哥

如何让它成为圣地亚哥?

function convert_case() {
    document.profile_form.city.value =
        document.profile_form.city.value.substr(0,1).toUpperCase() + 
        document.profile_form.city.value.substr(1).toLowerCase();
}

答案 1

这里有一个很好的答案:

function toTitleCase(str) {
    return str.replace(/\w\S*/g, function(txt){
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

或在 ES6 中:

var text = "foo bar loo zoo moo";
text = text.toLowerCase()
    .split(' ')
    .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
    .join(' ');

答案 2

你可以使用 CSS:

p.capitalize {text-transform:capitalize;}

更新(JS 解决方案):

根据Kamal Reddy的评论:

document.getElementById("myP").style.textTransform = "capitalize";