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

例如,当输入是“我是一个小茶壶”时,我期望“我是一个小茶壶”是输出。然而,该函数返回“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”));


当前回答

这里有一个简单的一行代码

const ucFirst = t => t.replace(/(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g, c => c.toUpperCase());

注意,它只改变每个单词的首字母大小写,你可能想这样使用它:

console.log(ucFirst('foO bAr'));
// FoO BAr

console.log(ucFirst('foO bAr'.toLowerCase()));
// Foo Bar

// works with accents too
console.log(ucFirst('éfoO bAr'));
// ÉfoO BAr

或者基于String。这里的原型是一个处理几种模式:

String.prototype.ucFirst = function (mode = 'eachWord') {
  const modes = {
    eachWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g,
    firstWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/,
    firstChar: /^[A-Za-zÀ-ÖØ-öø-ÿ]/,
    firstLetter: /[A-Za-zÀ-ÖØ-öø-ÿ]/,
  };

  if (mode in modes) {
    return this.replace(modes[mode], c => c.toUpperCase());
  } else {
    throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: ` + Object.keys(modes).join('|');
  }
};

console.log('eachWord', 'foO bAr'.ucFirst());
// FoO BAr

console.log('eachWord', 'foO bAr'.toLowerCase().ucFirst());
// Foo Bar

console.log('firstWord', '1foO bAr'.ucFirst('firstWord'));
// 1foO BAr

console.log('firstChar', '1foO bAr'.ucFirst('firstChar'));
// 1foO bAr

console.log('firstLetter', '1foO bAr'.ucFirst('firstLetter'));
// 1FoO bAr

编辑:

或者基于String。处理多种模式和可选的第二个参数来指定单词分隔符(String或RegExp)的原型:

String.prototype.ucFirst = function (mode = 'eachWord', wordSeparator = /\s/) {
  const letters = /[A-Za-zÀ-ÖØ-öø-ÿ]/;
  const ws =
    '^|' +
    (wordSeparator instanceof RegExp
      ? '(' + wordSeparator.source + ')'
      : // sanitize string for RegExp https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex#comment52837041_6969486
        '[' + wordSeparator.replace(/[[{}()*+?^$|\]\.\\]/g, '\\$&') + ']');

  const r =
    mode === 'firstLetter'
      ? letters
      : mode === 'firstChar'
      ? new RegExp('^' + letters.source)
      : mode === 'firstWord' || mode === 'eachWord'
      ? new RegExp(
          '(' + ws + ')' + letters.source,
          mode === 'eachWord' ? 'g' : undefined
        )
      : undefined;

  if (r) {
    return this.replace(r, (c) => c.toUpperCase());
  } else {
    throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: firstLetter|firstChar|firstWord|eachWord`;
  }
};

console.log("mike o'hara".ucFirst('eachWord', " \t\r\n\f\v'"));
// Mike O'Hara
console.log("mike o'hara".ucFirst('eachWord', /[\s']/));
// Mike O'Hara

其他回答

出于可读性考虑,我通常不喜欢使用regexp,而且我也尽量避免使用循环。我认为这是有可读性的。

function capitalizeFirstLetter(string) {
    return string && string.charAt(0).toUpperCase() + string.substring(1);
};

这里有一个完整而简单的解决方案:

String.prototype.replaceAt=function(index, replacement) {
        return this.substr(0, index) + replacement+ this.substr(index
  + replacement.length);
}
var str = 'k j g           u              i l  p';
function capitalizeAndRemoveMoreThanOneSpaceInAString() {
    for(let i  = 0; i < str.length-1; i++) {
        if(str[i] === ' ' && str[i+1] !== '')
            str = str.replaceAt(i+1, str[i+1].toUpperCase());
    }
    return str.replaceAt(0, str[0].toUpperCase()).replace(/\s+/g, ' ');
}
console.log(capitalizeAndRemoveMoreThanOneSpaceInAString(str));

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

 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(“你好世界”);

@somethingthere有一个更紧凑(和现代)的重写方案:

let titleCase = (str => str. tolowercase()。(' ') . map(分裂 c => c. charat (0). touppercase () + c.substring(1))。加入(' ')); 文档。write(titleCase(“我是一个更小的茶壶”));

我认为这条路会快一些;因为它不会拆分字符串并重新连接;只是用正则表达式。

var str = text.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());

解释:

(^\w{1}):匹配字符串的第一个字符 |:或者 (\s{1}\w{1}):匹配一个空格后面的一个字符 G:全部匹配 match => match. touppercase (): replace with can take function, so;将匹配替换为大写匹配