Home >Web Front-end >JS Tutorial >JavaScript趣题:Jaden Smith
Jaden Smith, son of Will Smith, is a film and television star.
In 2010, he starred in "Kung Fu Dream" and in 2013, he starred in "Return to Earth".
In addition to his movies, what is most interesting about him is his Twitter. He has a habit of capitalizing the first letter of each word when writing Twitter.
Your task is to convert the strings into Jaden Smith style, which are indeed quotes from him, but without capitalizing the first letter of each word.
For example:
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"
Okay, since we want the first letter of the word to be capitalized, let’s first extend a method like this:
if(typeof String.prototype.capitalizeFirst === "undefined"){ String.prototype.capitalizeFirst = function(){ return this.slice(0,1).toUpperCase() + this.slice(1); }; }
With this method, let’s look at the details ideas.
1. First split the string by spaces and break it into an array.
2. For each element of the array, that is, a word, call the first letter capitalization method we just wrote.
3. Reaggregate the array into a string and return.
Here, I used the ES5 map method, which just does the second point above.
String.prototype.toJadenCase = function () { return this.split(" ").map(function(e){ return e.capitalizeFirst(); }).join(" "); };
The above is the content of JavaScript Interesting Questions: Jaden Smith. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!