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

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


当前回答

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

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";

其他回答

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

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

原始代码:

function capi(str) {
    var s2 = str.trim().toLowerCase().split(' ');
    var s3 = [];
    s2.forEach(function(elem, i) {
        s3.push(elem.charAt(0).toUpperCase().concat(elem.substring(1)));
    });
    return s3.join(' ');
}
capi('JavaScript string exasd');

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

.capitalize {
    text-transform: capitalize;
}

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

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

这是一个简单的转换方法,可以传递一个值来获得所需的输出。

String.prototype.toChangeCase = function (type) {
    switch (type) {
        case 'upper-first':
            return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
        case 'upper-each':
            return this.split(' ').map(word => {
                return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
            }).join(' ');
        default:
            throw Error(`In order to get the output pass a value 'upper-first', 'upper-each'`);
    }
}

输出

"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-first')
"Capitalize first letter of each word in a sstring"


"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-each')
"Capitalize First Letter Of Each Word In A Sstring"

"Capitalize First Letter Of Each Word In A String".toChangeCase()
VM380:12 Uncaught Error: In order to get the output pass a value 'upper-first', 'upper-each'
    at String.toChangeCase (<anonymous>:12:19)
    at <anonymous>:16:52

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.