王培顺的博客&WangPeishun’s Blog

字符串的首字母大写,不能使用:

  1. toUpperCase()
  2. toLowerCase()

例子:

"string".capitalize() === "String" "hello World".capitalize() === "Hello World" "i love codewars".capitalize() === "I love codewars" "This sentence is already capitalized".capitalize() === "This sentence is already capitalized" "0123the first character of this sentence is not a letter".capitalize() === "0123the first character of this sentence is not a letter"

这次依旧没有我的答案。
1.

  • String.prototype.capitalize = function () {
  • let c = this.charCodeAt(0);
  • if (97 <= c && c <= 122) c -= 32;
  • return String.fromCharCode(c) + this.slice(1);
  • }

2.

  • String.prototype.capitalize = function(){
  • var map = {
  • a : 'A',
  • b : 'B',
  • c : 'C',
  • d : 'D',
  • e : 'E',
  • f : 'F',
  • g : 'G',
  • h : 'H',
  • i : 'I',
  • j : 'J',
  • k : 'K',
  • m : 'M',
  • n : 'N',
  • o : 'O',
  • p : 'P',
  • q : 'Q',
  • r : 'R',
  • s : 'S',
  • t : 'T',
  • u : 'U',
  • v : 'V',
  • w : 'W',
  • x : 'X',
  • y : 'Y',
  • z : 'Z'
  • };
  • return map[this[0]] ? map[this[0]] + this.slice(1) : this.toString();
  • };

3.

  • String.prototype.capitalize = function() {
  • return this.replace(/^[a-z]/, c => String.fromCharCode(c.charCodeAt(0)-32))
  • }

4.

  • String.prototype.capitalize = function() {
  • return /^[a-z]/.test(this) ? this.replace(this.charAt(0), String.fromCharCode(this.charCodeAt(0) - 32)) :
  • this.toString();
  • }

5.

  • String.prototype.capitalize = function()
  • {
  • var searchArray = 'abcdefghijklmnopqrstuvwxyz';
  • var replaceArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  • var array = this.split('');
  • var index = searchArray.indexOf(array[0]);
  • if (index > -1) array[0] = replaceArray[index];
  • return array.join('');
  • }

6.

  • String.prototype.capitalize = function() {
  • var alf = 'abcdefghijklmnopqrstuvwxyz';
  • var alfC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  • var self = this.split('');
  • if (alf.indexOf(self[0]) != -1) {
  • self[0] = alfC[alf.indexOf(self[0])];
  • }
  • return self.join('');
  • }

7.

  • String.prototype.capitalize = function() {
  • if (this.charCodeAt(0) >= 97 && this.charCodeAt(0) <= 122) {
  • return (String.fromCharCode(this.charCodeAt(0) - 32) + this.slice(1));
  • }
  • return this.toString();
  • }

8.

  • String.prototype.capitalize = function() {
  • if (this.charCodeAt() < 97 || this.charCodeAt() > 122) return this.toString();
  • return String.fromCharCode(this.charCodeAt() - 32) + this.substring(1);
  • };

标签: none

添加新评论