将字符串中的每个单词的首字母大写 - JavaScript

slu*_*rrr 50 javascript string capitalize charat

这个功能有什么问题?我失去了感谢你的帮助.

function titleCase(str) {
 var splitStr = str.toLowerCase().split(' ');
 for (var i = 0; i < splitStr.length; i++) {
   if (splitStr.length[i] < splitStr.length) {
     splitStr[i].charAt(0).toUpperCase();     
   }
      str = splitStr.join(' '); 
 }
return str;
}

titleCase("I'm a little tea pot");
Run Code Online (Sandbox Code Playgroud)

som*_*ere 93

您没有再次将更改分配给阵列,因此您的所有努力都是徒劳的.试试这个:

function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // You do not need to check if i is larger than splitStr length, as your for does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Directly return the joined string
   return splitStr.join(' '); 
}

document.write(titleCase("I'm a little tea pot"));
Run Code Online (Sandbox Code Playgroud)

  • 在 es6 中,你可以这样做,看起来更好一些:```myStr.toLowerCase().split(' ').map(word =&gt; word.charAt(0).toUpperCase() + word.substring(1) )).join(' ');``` (29认同)
  • 是的,我同意,目前的答案很好。所以我把它放在评论中,仅供新访客参考。 (3认同)
  • @PatrickMichaelsen 确实可以。不过我不会改变答案,它是从 2015 年开始的,我知道时代已经改变,但我会为后代保留它。另外,我也不会再这样写了:)但是我猜你可以随意发布你的答案作为你自己的答案吗? (2认同)

nim*_*sam 56

我认为这种方式应该更快;因为它不会拆分字符串并再次加入它;只是使用正则表达式。

var str = text.replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
Run Code Online (Sandbox Code Playgroud)

说明

  1. (^\w{1}): 匹配字符串的第一个字符
  2. |: 或者
  3. (\s{1}\w{1}): 匹配一个空格后的字符
  4. g: 全部匹配
  5. match => match.toUpperCase(): 替换为 can take 函数,所以;用大写匹配替换匹配


Mar*_*ude 46

你正在使复杂变得非常容易.您可以在CSS中添加:

 .capitalize {
    text-transform: capitalize;   
  }
Run Code Online (Sandbox Code Playgroud)

在javascript中,您可以将类添加到元素中

 document.getElementById("element").className="capitalize";
Run Code Online (Sandbox Code Playgroud)

  • 这是“仅显示”更改,字符串本身未更改。没有理由认为预期输出是 HTML 元素 - 没有迹象表明问题中的代码甚至在浏览器中! (15认同)
  • 感谢您的回复,但我正在尝试使用 javascript 来练习 @MarcosPérezGude (3认同)
  • 不幸的是,在某些情况下,如果该值为 20mm,而您使用大写,则它将是 20Mm。某些情况下 javascript 可能是唯一的方法。 (3认同)

chi*_*ens 32

最短的一个班轮(也非常快):

 text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());
Run Code Online (Sandbox Code Playgroud)

解释:

  • ^\w : 字符串的第一个字符
  • | : 或者
  • \s\w : 空格后的第一个字符
  • (^\w|\s\w) 捕捉模式。
  • g 标志:匹配所有出现。

如果您想确保其余部分为小写:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
Run Code Online (Sandbox Code Playgroud)

  • 这太棒了!正则表达式是最好的。您能详细说明一下这部分的作用吗?`m =&gt; m.toUpperCase()` (2认同)
  • @marcin2x4 `m` 匹配第一个字符,因此它使第一个字符大写。 (2认同)

Ste*_*ush 30

ES6版本:

const toTitleCase = (phrase) => {
  return phrase
    .toLowerCase()
    .split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
};

let result = toTitleCase('maRy hAd a lIttLe LaMb');
console.log(result);
Run Code Online (Sandbox Code Playgroud)

  • 我还认为您在一开始就缺少“toLowerCase()”,以防用户或字符串混合大小写。 (2认同)

waq*_*qas 18

如果你可以使用thirdparty库,那么lodash有一个帮助函数.

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)


ans*_*ngh 12

在ES6中使用箭头功能回答一线

const captialize = words => words.split(' ').map( w =>  w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')
Run Code Online (Sandbox Code Playgroud)

  • 好的!您可以使用“w[0]”使其更短。与正则表达式不同,它可以轻松地通过任何符号扩展,而不仅仅是“空格”。我的意思是 `(` `[` `"`,因为这些符号后面的字母也应该大写。所以感谢您的解决方案! (5认同)

Cha*_*nor 9

text-transform: capitalize;
Run Code Online (Sandbox Code Playgroud)

CSS 已经搞定了 :)


小智 6

也是一个不错的选择(特别是如果您使用的是freeCodeCamp):

function titleCase(str) {
  var wordsArray = str.toLowerCase().split(/\s+/);
  var upperCased = wordsArray.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substr(1);
  });
  return upperCased.join(" ");
}
Run Code Online (Sandbox Code Playgroud)


Jac*_*fin 6

--

您可以简单地使用正则表达式函数来更改每个字母的大写。通过V8 JIST优化,这应该被证明是快速且高效的内存。

// Only works on Latin-I strings
'tHe VeRy LOOong StRINg'.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, function(x){return x[0]==="'"||x[0]==="_"?x:String.fromCharCode(x.charCodeAt(0)^32)})
Run Code Online (Sandbox Code Playgroud)

或者,作为一个功能:

// Only works for Latin-I strings
var fromCharCode = String.fromCharCode;
var firstLetterOfWordRegExp = /\b[a-z]|['_][a-z]|\B[A-Z]/g;
function toLatin1UpperCase(x){ // avoid frequent anonymous inline functions
    var charCode = x.charCodeAt(0);
    return charCode===39 ? x : fromCharCode(charCode^32);
}
function titleCase(string){
    return string.replace(firstLetterOfWordRegExp, toLatin1UpperCase);
}
Run Code Online (Sandbox Code Playgroud)

根据此基准测试,该代码比Chrome中次佳的解决方案快33%以上。


// Only works on Latin-I strings
'tHe VeRy LOOong StRINg'.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, function(x){return x[0]==="'"||x[0]==="_"?x:String.fromCharCode(x.charCodeAt(0)^32)})
Run Code Online (Sandbox Code Playgroud)


Pat*_*Pat 5

此例程将处理带连字符的单词和带撇号的单词。

function titleCase(txt) {
    var firstLtr = 0;
    for (var i = 0;i < text.length;i++) {
        if (i == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
            firstLtr = 2;
        if (firstLtr == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
            firstLtr = 2;
        if (firstLtr == 1 &&/[^a-zA-Z]/.test(text.charAt(i))){
            if (text.charAt(i) == "'") {
                if (i + 2 == text.length &&/[a-zA-Z]/.test(text.charAt(i + 1)))
                    firstLtr = 3;
                else if (i + 2 < text.length &&/[^a-zA-Z]/.test(text.charAt(i + 2)))
                    firstLtr = 3;
            }
        if (firstLtr == 3)
            firstLtr = 1;
        else
            firstLtr = 0;
        }
        if (firstLtr == 2) {
            firstLtr = 1;
            text = text.substr(0, i) + text.charAt(i).toUpperCase() + text.substr(i + 1);
        }
        else {
            text = text.substr(0, i) + text.charAt(i).toLowerCase() + text.substr(i + 1);
        }
    }
}

titleCase("pAt o'Neil's");
// returns "Pat O'Neil's";
Run Code Online (Sandbox Code Playgroud)


Art*_*ens 5

ES2015版本:

const titleCase = title => title
    .split(/ /g).map(word => 
        `${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
    .join("");
Run Code Online (Sandbox Code Playgroud)

  • 我现在才看到它,而且非常整洁,但是我认为您需要使用`“”`而不是`“”`加入,否则您会得到一个大字眼,不是吗? (3认同)

小智 5

由于可读性,我通常不喜欢使用正则表达式,而且我也尝试远离循环。我认为这是一种可读性。

function capitalizeFirstLetter(string) {
    return string && string.charAt(0).toUpperCase() + string.substring(1);
};
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用现代 JS 语法,这可以让您的生活更轻松。这是我针对给定问题的代码片段:

const capitalizeString = string => string.split(' ').map(item => item.replace(item.charAt(0), item.charAt(0).toUpperCase())).join(' ');
capitalizeString('Hi! i am aditya shrivastwa')
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

95654 次

最近记录:

6 年,1 月 前