JavaScript字符串单词首字母大写的实现方式

 mobiledu2502856013 发布于 2022-11-21 22:47

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

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

求接龙。

6 个回答
  •     // 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(" ");
        }
    2022-11-21 23:18 回答
  • 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();});
    }
    2022-11-21 23:18 回答
  • 楼主如果用正则表达式的话,下面的表达应该更简单

    String.prototype.firstUpperCase=function(){
        return this.replace(/^\S/,function(s){return s.toUpperCase();});
    }
    
    2022-11-21 23:18 回答
  • String.prototype.firstUpperCase = function () {
      return this.toString()[0].toUpperCase() + this.toString().slice(1);
    }
    

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

    2022-11-21 23:18 回答
  • 其实有很多方法。
    最常见的,最基础的:

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

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

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

    是不是觉得很简洁?

    2022-11-21 23:18 回答
  • CSS 完全搞定啊 text-transform: capitalize;
    这么简单的功能 还用js 就太浪费累

    2022-11-21 23:18 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有