我想使用javascript函数来大写每个单词的第一个字母。
例如:
THIS IS A TEST ---> This Is A Test
this is a TEST ---> This Is A Test
this is a test ---> This Is A Test什么是简单的javascript函数?
发布于 2011-10-22 01:09:05
这是我用来完成这项工作的一小段代码
var str = 'this is an example';
str.replace(/\b./g, function(m){ return m.toUpperCase(); });但是John Resig做了一个非常棒的脚本,它处理了很多案例http://ejohn.org/blog/title-capitalization-in-javascript/
更新
ES6+答案:
str.split(' ').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');
可能还有比这更好的方法。它将在重音字符上工作。
发布于 2011-09-19 15:56:21
function capitalizeEachWord(str)
{
   var words = str.split(" ");
   var arr = [];
   for (i in words)
   {
      temp = words[i].toLowerCase();
      temp = temp.charAt(0).toUpperCase() + temp.substring(1);
      arr.push(temp);
   }
   return arr.join(" ");
}发布于 2011-09-19 15:35:46
"tHiS iS a tESt".replace(/[^\s]+/g, function(str){ 
    return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
  });其他变体:
"tHiS iS a tESt".replace(/(\S)(\S*)/g, function($0,$1,$2){ 
    return $1.toUpperCase()+$2.toLowerCase();
  });https://stackoverflow.com/questions/7467381
复制相似问题