将字符串中的每个单词的首字母大写 - JavaScript

时间:2015-09-15 14:52:59

标签: javascript string capitalize charat

这个功能有什么问题?我失去了感谢你的帮助。

function titleCase(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(' '); 
 }
return str;
}

titleCase("I'm a little tea pot");

38 个答案:

答案 0 :(得分:66)

您没有再次将更改分配给阵列,因此您的所有努力都是徒劳的。试试这个:

&#13;
&#13;
function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // You do not need to check if i is larger than splitStr length, as your for does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Directly return the joined string
   return splitStr.join(' '); 
}

document.write(titleCase("I'm a little tea pot"));
&#13;
&#13;
&#13;

答案 1 :(得分:30)

你正在使复杂变得非常容易。您可以在CSS中添加:

 .capitalize {
    text-transform: capitalize;   
  }

在javascript中,您可以将该类添加到元素

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

答案 2 :(得分:20)

ES6版本:

&#13;
&#13;
const toTitleCase = (phrase) => {
  return phrase
    .toLowerCase()
    .split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
};

let result = toTitleCase('maRy hAd a lIttLe LaMb');
console.log(result);
&#13;
&#13;
&#13;

答案 3 :(得分:16)

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

PodSecurityPolicy

说明:

  • text.replace(/(^\w|\s\w)/g, m => m.toUpperCase()); :字符串的第一个字符
  • ^\w:或
  • |:空格后的第一个字符
  • \s\w捕获图案。
  • (^\w|\s\w)标志:匹配所有匹配项。

如果要确保其余部分都小写:

g

答案 4 :(得分:14)

如果你可以使用第三方库,那么lodash有一个帮助函数。

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>

答案 5 :(得分:4)

您可以使用现代JS语法,这可以使您的生活更加轻松。这是给定问题的代码片段:

const capitalizeString = string => string.split(' ').map(item => item.replace(item.charAt(0), item.charAt(0).toUpperCase())).join(' ');
capitalizeString('Hi! i am aditya shrivastwa')

答案 6 :(得分:4)

我认为这种方式应该更快;因为它不会拆分字符串并再次连接它;只是使用正则表达式。

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

说明

  1. (^\w{1}):匹配字符串的第一个字符
  2. |:或
  3. (\s{1}\w{1}):匹配一个空格后的一个字符
  4. g:全部匹配
  5. match => match.toUpperCase():替换为can take函数,因此;用大写替换替换匹配

答案 7 :(得分:4)

在ES6中使用箭头功能的一线回答

const captialize = words => words.split(' ').map( w =>  w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')

答案 8 :(得分:4)

您可以简单地使用正则表达式函数来更改每个字母的大小写。通过V8 JIST优化,这应该证明是快速和内存效率。

// Only works on Latin-I strings
'tHe VeRy LOOong StRINg'.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, function(x){return x[0]==="'"||x[0]==="_"?x:String.fromCharCode(x.charCodeAt(0)^32)})

或者,作为一个功能:

// Only works for Latin-I strings
var fromCharCode = String.fromCharCode;
var firstLetterOfWordRegExp = /\b[a-z]|['_][a-z]|\B[A-Z]/g;
function toLatin1UpperCase(x){ // avoid frequent anonymous inline functions
    var charCode = x.charCodeAt(0);
    return charCode===39 ? x : fromCharCode(charCode^32);
}
function titleCase(string){
    string.replace(firstLetterOfWordRegExp, toLatin1UpperCase);
}


演示

&#13;
&#13;
<textarea id="input" type="text">I'm a little tea pot</textarea><br /><br />
<textarea id="output" type="text" readonly=""></textarea>
<script>
(function(){
    "use strict"
    var fromCode = String.fromCharCode;
    function upper(x){return x[0]==="'"?x:fromCode(x.charCodeAt(0) ^ 32)}
    (input.oninput = function(){
      output.value = input.value.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, upper);
    })();
})();
</script>
&#13;
&#13;
&#13;

答案 9 :(得分:3)

ES2015版本:

commands.runrawcommand("SET key value");

答案 10 :(得分:3)

ES6语法

const captilizeAllWords = (sentence) => {
  if (typeof sentence !== "string") return sentence;
  return sentence.split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}


captilizeAllWords('Something is going on here')

答案 11 :(得分:2)

这里是一个简单的单线

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.prototype,这里是一种处理多种模式的方法:

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

答案 12 :(得分:2)

TypeScript 粗箭头 FTW

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

答案 13 :(得分:2)

text-transform: capitalize;

Css知道了:)

答案 14 :(得分:2)

或者可以使用replace()完成,并用“upperCase”替换每个单词的第一个字母。

function titleCase(str) {
  return str.toLowerCase().split(' ').map(function(word) {
     return word.replace(word[0], word[0].toUpperCase());
      }).join(' ');
}

titleCase("I'm a little tea pot");

答案 15 :(得分:2)

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

答案 16 :(得分:2)

由于可读性,我通常不喜欢使用正则表达式,而且我也试图远离循环。我认为这有点可读。

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

答案 17 :(得分:1)

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

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”); //返回“Pat O'Neil's”;

答案 18 :(得分:1)

基本上,这是使用map函数的方式,它与接受的答案相同,但没有for-loop。因此,可以节省几行代码。

function titleCase(text) {
  if (!text) return text;
  if (typeof text !== 'string') throw "invalid argument";

  return text.toLowerCase().split(' ').map(value => {
    return value.charAt(0).toUpperCase() + value.substring(1);
  }).join(' ');
}

console.log(titleCase("I'm A little tea pot"));

答案 19 :(得分:1)

下面的函数除了尝试将所有单词的所有首字母(即通过正则表达式定义\w+转换为大写字母)之外,不会更改字符串的任何其他部分。

这意味着不一定不一定将单词转换为Titlecase,但是恰恰是问题标题所说的:“将字符串中每个单词的首字母大写-JavaScript”

  • 不要分割字符串
  • 通过与\w+等效的正则表达式[A-Za-z0-9_]+确定每个word
    • 仅将功能String.prototype.toUpperCase()应用于每个单词的第一个字符。
function first_char_to_uppercase(argument) {
  return argument.replace(/\w+/g, function(word) {
    return word.charAt(0).toUpperCase() + word.slice(1);
  });
}

示例:

first_char_to_uppercase("I'm a little tea pot");
// "I'M A Little Tea Pot"
// This may look wrong to you, but was the intended result for me
// You may wanna extend the regex to get the result you desire, e.g., /[\w']+/

first_char_to_uppercase("maRy hAd a lIttLe LaMb");
// "MaRy HAd A LIttLe LaMb"
// Again, it does not convert words to Titlecase

first_char_to_uppercase(
  "ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples"
);
// "ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples"

first_char_to_uppercase("…n1=orangesFromSPAIN&&n2!='a sub-string inside'");
// "…N1=OrangesFromSPAIN&&N2!='A Sub-String Inside'"

first_char_to_uppercase("snake_case_example_.Train-case-example…");
// "Snake_case_example_.Train-Case-Example…"
// Note that underscore _ is part of the RegEx \w+

first_char_to_uppercase(
  "Capitalize First Letter of each word in a String - JavaScript"
);
// "Capitalize First Letter Of Each Word In A String - JavaScript"

编辑2019-02-07:如果您想要实际的标题大小写(即仅首字母大写,其他字母均小写):

function titlecase_all_words(argument) {
  return argument.replace(/\w+/g, function(word) {
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  });
}

同时显示两个示例:

test_phrases = [
  "I'm a little tea pot",
  "maRy hAd a lIttLe LaMb",
  "ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples",
  "…n1=orangesFromSPAIN&&n2!='a sub-string inside'",
  "snake_case_example_.Train-case-example…",
  "Capitalize First Letter of each word in a String - JavaScript"
];
for (el in test_phrases) {
  let phrase = test_phrases[el];
  console.log(
    phrase,
    "<- input phrase\n",
    first_char_to_uppercase(phrase),
    "<- first_char_to_uppercase\n",
    titlecase_all_words(phrase),
    "<- titlecase_all_words\n "
  );
}

// I'm a little tea pot <- input phrase
// I'M A Little Tea Pot <- first_char_to_uppercase
// I'M A Little Tea Pot <- titlecase_all_words

// maRy hAd a lIttLe LaMb <- input phrase
// MaRy HAd A LIttLe LaMb <- first_char_to_uppercase
// Mary Had A Little Lamb <- titlecase_all_words

// ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples <- input phrase
// ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples <- first_char_to_uppercase
// Examplex: Camelcase/Uppercase&Lowercase,Exampley:N0=Apples <- titlecase_all_words

// …n1=orangesFromSPAIN&&n2!='a sub-string inside' <- input phrase
// …N1=OrangesFromSPAIN&&N2!='A Sub-String Inside' <- first_char_to_uppercase
// …N1=Orangesfromspain&&N2!='A Sub-String Inside' <- titlecase_all_words

// snake_case_example_.Train-case-example… <- input phrase
// Snake_case_example_.Train-Case-Example… <- first_char_to_uppercase
// Snake_case_example_.Train-Case-Example… <- titlecase_all_words

// Capitalize First Letter of each word in a String - JavaScript <- input phrase
// Capitalize First Letter Of Each Word In A String - JavaScript <- first_char_to_uppercase
// Capitalize First Letter Of Each Word In A String - Javascript <- titlecase_all_words

答案 20 :(得分:1)

function titleCase(str) {

var myString = str.toLowerCase().split(' ');
for (var i = 0; i < myString.length; i++) {
    var subString = myString[i].split('');
    for (var j = 0; j < subString.length; j++) {
        subString[0] = subString[0].toUpperCase();

    }
    myString[i] = subString.join('');
}

return myString.join(' '); }

答案 21 :(得分:1)

let str = "I'm a little tea pot";

str = str.toLowerCase();

并将css属性text-transform: capitalize;添加到相应的元素。

答案 22 :(得分:1)

let cap = (str) => {
  let arr = str.split(' ');
  arr.forEach(function(item, index) {
    arr[index] = item.replace(item[0], item[0].toUpperCase());
  });

  return arr.join(' ');
};

console.log(cap("I'm a little tea pot"));

快速可读版本,请参见基准http://jsben.ch/k3JVz enter image description here

答案 23 :(得分:1)

replace()与RegExp

一起使用
function titleCase(str) {

  var newStr = str.toLowerCase().replace(/./, (x) => x.toUpperCase()).replace(/[^']\b\w/g, (y) => y.toUpperCase());


console.log(newStr);

}

titleCase("I'm a little tea pot")

答案 24 :(得分:1)

原始代码:

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('js string exasd');

答案 25 :(得分:0)

完整而简单的解决方案在这里:

    var str = 'k j g           u              i l  p';
function capitalizeAndRemoveMoreThanOneSpaceInAString() {
    String.prototype.replaceAt=function(index, replacement) {
        return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
    }
    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));

答案 26 :(得分:0)

我已经使用下面的代码完成了此操作,希望对您有所帮助:

<p id="p1">This is a paragraph.</p>

<script>
   const capitalize = (mySentence) => {
      const words = mySentence.split(" ");
      for (let i = 0; i < words.length; i++) {
         words[i] = words[i][0].toUpperCase() + words[i].substr(1);
      }
      return words.join(" ");
   };  
   const result = capitalize('This is a sample text');
   document.getElementById("p1").innerHTML = result;
</script>

答案 27 :(得分:0)

你可以在一行中使用 toUpperCase 使用 map 来做这样的简单方法:

    text.split(' ').map(w => { let t = w.split(''); t[0] = t[0].toUpperCase(); return t.join('') }).join(' ')

答案 28 :(得分:0)

/* 1. Transform your string into lower case
2. Split your string into an array. Notice the white space i'm using for separator
3. Iterate the new array, and assign the current iteration value (array[c]) a new formatted string:
 - With the sentence: array[c][0].toUpperCase() the first letter of the string converts to upper case.
 - With the sentence: array[c].substring(1) we get the rest of the string (from the second letter index to the last one).
 - The "add" (+) character is for concatenate both strings. 
4. return array.join(' ') // returns the formatted array like a new string.*/


function titleCase(str){
    str = str.toLowerCase();
    var array = str.split(' ');
    for(var c = 0; c < array.length; c++){
        array[c] = array[c][0].toUpperCase() + array[c].substring(1);
    }
return array.join(' ');
}

titleCase("I'm a little tea pot");

答案 29 :(得分:0)

我在这里使用了replace()函数。

function titleCase(str){
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

答案 30 :(得分:0)

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

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

答案 31 :(得分:0)

这里我使用了三个功能toLowerCase()toUpperCase()replace(regex,replacer)

function titleCase(str) { 
     return str.toLowerCase().replace(/^(\w)|\s(\w)/g, (grp) => grp.toUpperCase()); 
}

titleCase("I'm a little tea pot");

答案 32 :(得分:0)

<DeploymentOptions xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:ddl2="http://schemas.microsoft.com/analysisservices/2003/engine/2" 
xmlns:ddl2_2="http://schemas.microsoft.com/analysisservices/2003/engine/2/2" 
xmlns:ddl100_100="http://schemas.microsoft.com/analysisservices/2008/engine/100/100" 
xmlns:ddl200="http://schemas.microsoft.com/analysisservices/2010/engine/200" 
xmlns:ddl200_200="http://schemas.microsoft.com/analysisservices/2010/engine/200/200">
  <PartitionDeployment>DeployPartitions</PartitionDeployment>
  <RoleDeployment>DeployRolesRetainMembers</RoleDeployment>
  <ProcessingOption>DoNotProcess</ProcessingOption>
  <ADALCache>None</ADALCache>
  <ConfigurationSettingsDeployment>Deploy</ConfigurationSettingsDeployment>
  <OptimizationSettingsDeployment>Deploy</OptimizationSettingsDeployment>
  <WriteBackTableCreation>UseExisting</WriteBackTableCreation>
</DeploymentOptions>

答案 33 :(得分:0)

下面是另一种大写字符串中每个单词的第一个字母的方法。

使用原型为String对象创建一个自定义方法。

  String.prototype.capitalize = function() {
      var c = '';
      var s = this.split(' ');
      for (var i = 0; i < s.length; i++) {
          c+= s[i].charAt(0).toUpperCase() + s[i].slice(1) + ' ';
      }
      return c;
  }
  var name = "john doe";
  document.write(name.capitalize());

答案 34 :(得分:0)

function LetterCapitalize(str) { 
  return str.split(" ").map(item=>item.substring(0,1).toUpperCase()+item.substring(1)).join(" ")
}

答案 35 :(得分:0)

请检查以下代码。

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

答案 36 :(得分:0)

从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);

说明:
1.首先,我们将字符串“test test test”传递给我们的函数“titleCase” 2.我们在空格基础上拆分字符串,因此第一个函数“split”的结果将是[“test”,“test”,“test”] 当我们得到一个数组时,我们使用map函数来处理数组中的每个单词。我们将第一个字符大写并为其添加剩余字符 4.在最后,我们使用空格连接数组,因为我们用sapce分割字符串。

答案 37 :(得分:0)

@ somethingthere建议的解决方案更紧凑(和现代)的重写:

function titleCase(str) {
    return str.toLowerCase().split(' ').map(function(chunk){
        return chunk.charAt(0).toUpperCase() + chunk.substring(1);
    }).join(' ');
}
    
document.write(titleCase("I'm an even smaller tea pot"));