字串大小寫互換方法
阿新 • • 發佈:2018-11-30
1 String.prototype.toAlternatingCase = function () { 2 return this.split("").map(a => a === a.toUpperCase() ? 3 a.toLowerCase(): a.toUpperCase()).join('') 4 }
該方法中判斷當前字母是大寫字母還是小寫字母的方法是:
a === a.toUpperCase() 或者 a === a.toLowerCase()
String.prototype.toAlternatingCase = function() { return this.replace(/[a-zA-Z]/g, (i) => i>='a' ? i.toUpperCase():i.toLowerCase()) }
上面的方法中判斷大小寫的方法是:
在搜查出的大小寫字母中,char >= 'a' 是小寫字母;反之值大寫字母。
注意: 1)toUpperCase(),toLowerCase()對非字母的字元不產生作用,所以判斷的時候不需要char >= 'a' && char <= 'z'
2) 不能連寫 ''a'<=char<='z',而應該寫成char >= 'a' && char <= 'z'