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


当前回答

这个解决方案不使用正则表达式,支持重音字符,而且几乎所有浏览器都支持。

function capitalizeIt(str) {
    if (str && typeof(str) === "string") {
        str = str.split(" ");    
        for (var i = 0, x = str.length; i < x; i++) {
            if (str[i]) {
                str[i] = str[i][0].toUpperCase() + str[i].substr(1);
            }
        }
        return str.join(" ");
    } else {
        return str;
    }
}    

用法:

console.log(大写it ('çao 2nd inside Javascript program '));

输出:

Çao第2内部Javascript程序

其他回答

使用JavaScript和html

String.prototype.capitalize = function() { 返回this.replace (/ (^ | \ s) ([a - z]) / g函数(m, p1, p2) { return p1 + p2.toUpperCase(); }); }; <form name="form1" method="post"> <input name="instring" type="text" value="this is the text string" size="30"> <input type="button" name="Capitalize" value="Capitalize >>" onclick="form1.outstring.value=form1.instring.value.capitalize();" > <input name="outstring" type="text" value="" size="30"> > < /形式

基本上,你可以用string。capitalize()它会大写每个单词的第一个字母。

来源:http://www.mediacollege.com/internet/javascript/text/case-capitalize.html

这应该涵盖了最基本的用例。

const capitalize = (str) => {
    if (typeof str !== 'string') {
      throw Error('Feed me string')
    } else if (!str) {
      return ''
    } else {
      return str
        .split(' ')
        .map(s => {
            if (s.length == 1 ) {
                return s.toUpperCase()
            } else {
                const firstLetter = s.split('')[0].toUpperCase()
                const restOfStr = s.substr(1, s.length).toLowerCase()
                return firstLetter + restOfStr
            }     
        })
        .join(' ')
    }
}


capitalize('THIS IS A BOOK') // => This Is A Book
capitalize('this is a book') // => This Is A Book
capitalize('a 2nd 5 hour boOk thIs weEk') // => A 2nd 5 Hour Book This Week

编辑:改进了映射的可读性。

我的解决方案:

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'

John Resig (jQuery的成名者)将John Gruber编写的perl脚本移植到JavaScript。这个脚本以一种更聪明的方式大写,它没有大写像“of”和“and”这样的小词。

你可以在这里找到它:Title资本化JavaScript

用这个:

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 >