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

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

其他回答

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

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

TypeScript肥箭头FTW

export const formatTitleCase = (string: string) =>
    string
        .toLowerCase()
        .split(" ")
        .map((word) => word.charAt(0).toUpperCase() + word.substring(1))
        .join(" ");

也是一个很好的选择(特别是如果你使用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(" ");
}

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.

var str = "hello world"
var result = str.split(" ").map(element => {
    return element[0].toUpperCase() + element.slice(1);
});
result = result.join(" ")
console.log(result);