JavaScript字符串单词首字母大写的实现方式
天蓬老师
天蓬老师 2017-04-10 15:35:13
[JavaScript讨论组]

下面的代码是我的实现,不知道有没有更好的实现方案。

javascriptString.prototype.firstUpperCase = function(){
    return this.replace(/\b(\w)(\w*)/g, function($0, $1, $2) {
        return $1.toUpperCase() + $2.toLowerCase();
    });
}

求接龙。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(6)
黄舟

CSS 完全搞定啊 text-transform: capitalize;
这么简单的功能 还用js 就太浪费累

天蓬老师

其实有很多方法。
最常见的,最基础的:

1.先split()成数组。
2.将数组中的元素全部小写化。(toLowerCase())
3.使用replace(),toUpperCase()方法将每一项首字母大写化,之后join()就可以了。
但是这样确实很麻烦。

正在学习ES6中,ES6里面解决这个方案这样写就可以了。

function firstUpperCase(str) {
  return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

是不是觉得很简洁?

伊谢尔伦
String.prototype.firstUpperCase = function () {
  return this.toString()[0].toUpperCase() + this.toString().slice(1);
}

不改变原字符串。(暂时想不到改变原字符串的方式,因为我记得字符串是只读的)

天蓬老师

楼主如果用正则表达式的话,下面的表达应该更简单

String.prototype.firstUpperCase=function(){
    return this.replace(/^\S/,function(s){return s.toUpperCase();});
}
PHPz

why not use CSS? text-transform: capitalize;can solve this.
you can also use this function:

function firstUpperCase(str) {
  return str.toLowerCase().replace(/\b[a-z]/g,function(s){return s.toUpperCase();});
  }
  

but if only want to change the initials of the whole strings,try this:

function firstUpperCase(str) {
  return str.toLowerCase().replace(/^\S/g,function(s){return s.toUpperCase();});
}
天蓬老师
    // RegExp
    const firstUpperCase = (str) => {
      return str.replace(/(^|\s)[a-z]/g, (y) => y.toUpperCase());
    }
    
    // RegExp && splits
    const firstUpperCase2 = (str) => {
      const splits = str.split(" ");
      return splits.map((x) => x.replace(/[a-z]/, (y) => y.toUpperCase())).join(" ");
    }
    
    // charAt && substr && splits
    const firstUpperCase3 = (str) => {
      const splits = str.split(" ");
      return splits.map((x) => x.charAt(0).toUpperCase() + x.substr(1)).join(" ");
    }
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号