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

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


当前回答

这是一个使用现代javascript实践来提高可读性的完美例子。还没有看到一个减少版本在这里,但这是我使用的。这既是一个咖喱单行和非常可读

sentence
    .trim().toLowerCase()
    .split(' ')
    .reduce((sentence, word) => `${sentence} ${word[0].toUpperCase()}${word.substring(1)}`, '')
    .trim()

其他回答

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

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;将匹配替换为大写匹配

ECMAScript 6版本:

const toTitleCase =(短语)=> { 返回的短语 .toLowerCase () .split (' ') .map(word => word. charat (0).toUpperCase() + word.slice(1)) . join (' '); }; let result = toTitleCase('maRy have a lIttLe LaMb'); console.log(结果);

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

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

你把复杂变得很简单了。你可以在你的CSS中添加这个:

.capitalize {
    text-transform: capitalize;
}

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

 document.getElementById("element").className = "capitalize";

试试这个函数:

const capitializeName = (name) => {
 
     const splitName = name.split(' ');
        const namesUpper = [];

    for (const n of splitName) {
        namesUpper.push(n[0].toUpperCase() + n.slice(1));
    }
    console.log(namesUpper.join(' '));
};

capitializeName('jahid bhuiyan');