大写字符串

时间:2017-01-19 15:35:15

标签: javascript chunks

我知道CSS属性text-transform: capitalize,但有人可以帮我复制这个使用Javascript吗?

我想将一个参数传递给我的函数,该函数将返回字符串,每个单词的首字母大写。

我已经做到这一点了,但是我一直试图将我的数组字符串分解成块:

function upper(x){
  x = x.split(" "); 

  // this function should return chunks but when called I'm getting undefined
  Array.prototype.chunk = function ( n ) {
      return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
  };

  x = x.chunk;

}

upper("chimpanzees like cigars")

在块之后我猜我需要再次将每个块拆分为第一个字符和剩余字符,在第一个字符上使用.toUpperCase(),将其与其余字符连接起来,然后加入再次打成一个字符串?

是否有更简单的方法可以做到这一点?

6 个答案:

答案 0 :(得分:4)

我想出了一个字和一个数组字的解决方案。它还将确保所有其他字母都是小写的以获得良好的衡量标准。我也使用了Airbnb风格指南。我希望这有帮助!



const mixedArr = ['foo', 'bAr', 'Bas', 'toTESmaGoaTs'];
const word = 'taMpa';

function capitalizeOne(str) {
  return str.charAt(0).toUpperCase().concat(str.slice(1).toLowerCase());
}


function capitalizeMany(args) {
  return args.map(e => {
    return e.charAt(0).toUpperCase().concat(e.slice(1).toLowerCase());
  });
};

const cappedSingle = capitalizeOne(word);
const cappedMany = capitalizeMany(mixedArr);

console.log(cappedSingle);
console.log(cappedMany);




答案 1 :(得分:3)

map功能非常适用于此。

w[0].toUpperCase():使用此项来大写每个单词的第一个字母

w.slice(1):从

上的第二个字符返回字符串

EDGE案例

如果用户未输入字符串,则map功能将不起作用,并且将引发错误。通过检查用户是否确实输入了某些内容,可以防止这种情况。

var userInput = prompt("Enter a string");

var capitalizedString = userInput == "" ? "Invalid String" :
 userInput.split(/\s+/).map(w => w[0].toUpperCase() + w.slice(1)).join(' ');

console.log(capitalizedString);

答案 2 :(得分:3)

您可以使用以下不使用正则表达式的解决方案。

@media screen and (max-width:875px) {
.navbar.responsive {
  position:fixed;
  width: 100%;
  height: 100vh;
  background-color: rgba(236,201,205, 1);
  transition: background-color .6s;
  overflow: scroll; // Set overflow to scroll
}
}

答案 3 :(得分:0)

您可能想尝试使用正则表达式方法:

function upperCaseFirst(value) {
    var regex = /(\b[a-z](?!\s))/g;
    return value ? value.replace(regex, function (v) {
      return v.toUpperCase();
    }) : '';
}

这将获取句子上每个单词的第一个字母并将其大写,但如果您只想要句子的第一个字母,则可以在正则表达式声明的末尾删除g修饰符。

答案 4 :(得分:0)

"abcd efg ijk lmn".replace(/\b(.)/g, (m => m.toUpperCase())) // Abcd Efg Ijk Lmn

答案 5 :(得分:0)

或者您可以仅迭代字符串并完成工作:

function capitalize(lowerStr){
  var result = "";
  var isSpacePrevious = false;
  for (var i=0; i<lowerStr.length; i++){
      if (i== 0 || isSpacePrevious){
         result += lowerStr[i].toUpperCase();
         isSpacePrevious = false;
         continue;
      }
      if (lowerStr[i] === ' '){
          isSpacePrevious = true;
      }  
      result +=  lowerStr[i];
  }
  return result;
}