我试图写一个函数,大写字符串中每个单词的第一个字母(将字符串转换为标题情况)。

例如,当输入是“我是一个小茶壶”时,我期望“我是一个小茶壶”是输出。然而,该函数返回“i'm a little tea pot”。

这是我的代码:

函数标题案例(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(“ ”); } 返回 str; } console.log(titleCase(“I'm a Little Teapot”));


当前回答

使用正则表达式,处理特殊字符,如ñ,中间有多个空格:/(^.|\s+.)/g

Let text = "ñora ñora" console.log (text.toLowerCase () .replace (/ (^ | \ s +。)/ g m = > m.toUpperCase ()))

其他回答

如果可行,请使用text-transform: capitalize;CSS属性将文本转换为标题大小写。

如果您可以同样依赖CSS来实现相同的结果,那么与JavaScript选项相比,这种操作成本更低。

《我是一个小茶壶》是以下片段的结果。

<p style="text-transform: capitalize;">I'm a little tea pot</p>

最短的一行(也非常快):

 text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

解释:

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


如果你想确保剩下的是小写的:

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

使用示例:

几点toTitleCase = str = > str。replace (/ s (^ w | \ \ w) (s *) / g, (m1, m2) = >的m1 toUpperCase () + m2。toLowerCase () 控制台日志。(toTitleCase(“你好世界”);

ECMAScript 6版本:

title
    .split(/ /g).map(word =>
        `${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
    .join(" ");

ECMA2017或ES8

const titleCase = (string) => { return string .split(' ') .map(word => word.substr(0,1).toUpperCase() + word.substr(1,word.length)) .join(' '); }; let result = titleCase('test test test'); console.log(result); Explanation: 1. First, we pass the string "test test test" to our function "titleCase". 2. We split a string on the space basis so the result of first function "split" will be ["test","test","test"] 3. As we got an array, we used map function for manipulation each word in the array. We capitalize the first character and add remaining character to it. 4. In the last, we join the array using space as we split the string by sapce.

请检查下面的代码。

function titleCase(str) {
  var splitStr = str.toLowerCase().split(' ');
  var nstr = ""; 
  for (var i = 0; i < splitStr.length; i++) {
    nstr +=  (splitStr[i].charAt(0).toUpperCase()+ splitStr[i].slice(1) + " 
    ");
  }
  console.log(nstr);
}

var strng = "this is a new demo for checking the string";
titleCase(strng);