7kyu Jaden Casing Strings

题目:api

Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word.this

Jaden Smith是威尔史密斯的儿子,他是电影空手道小子(2010)和地球(2013)的明星。Jaden也因他的一些哲学而闻名,他经过Twitter发布了他的哲学。当他在Twitter上写做时,他几乎老是把每一个词都大写。spa

Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.prototype

你的任务是把字符串转换成Jaden Smith的写做方式。这些字符串是Jaden Smith的实际引用,但它们并无像他最初输入的那样大写。code

Example:blog

Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased:     "How Can Mirrors Be Real If Our Eyes Aren't Real"

Sample Tests:字符串

var str = "How can mirrors be real if our eyes aren't real";
Test.assertEquals(str.toJadenCase(), "How Can Mirrors Be Real If Our Eyes Aren't Real");

答案:string

// 1
String.prototype.toJadenCase = function () {
  var str = this;
  var arr = str.toLowerCase().split(' ');
  for(i = 0; i < arr.length; i++) {
    arr[i] = arr[i].slice(0,1).toUpperCase() + arr[i].slice(1);
  }
  return arr.join(' ');
};

// 2
String.prototype.toJadenCase = function () {
    return this.split(" ").map((word) => {
        return word.charAt().toUpperCase() + word.slice(1);
    }).join(" ");
}

// 3  
// ^    匹配字符串的开始  
// \s匹配任意的空白符,包括空格,制表符(Tab),换行符,中文全角空格等
String.prototype.toJadenCase = function () {
    return this.replace(/(^|\s)[a-z]/g, function(x) {
        return x.toUpperCase();
    });
}
相关文章
相关标签/搜索