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();
    });
}
相關文章
相關標籤/搜索