首页 文章

如何将每个单词的首字母大写,如双字城市? [重复]

提问于
浏览
208

这个问题在这里已有答案:

当这个城市有一个词时,我的JS很好:

  • cHIcaGO ==>芝加哥

但是当它的时候

  • san diego ==> San diego

我怎样才能成为圣地亚哥?

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();
}

4 回答

  • 21

    有一个很好的答案here

    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(' ');
    
  • 551

    你可以使用CSS:

    p.capitalize {text-transform:capitalize;}
    
  • 123
    function convertCase(str) {
      var lower = String(str).toLowerCase();
      return lower.replace(/(^| )(\w)/g, function(x) {
        return x.toUpperCase();
      });
    }
    
  • 6

    JavaScript函数:

    String.prototype.capitalize = function(){
           return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
          };
    

    要使用此功能:

    capitalizedString = someString.toLowerCase().capitalize();
    

    此外,这将适用于多个单词字符串 .

    为了确保将转换后的城市名称注入数据库,小写和首字母大写,那么在将其发送到服务器端之前,您需要使用JavaScript . CSS只是样式,但实际数据仍然是预先设置的样式 . 看一下这个jsfiddle示例,并比较警报消息和样式化输出 .

相关问题