在JavaScript中,我们可以编写自己的自定义函数并将其分配给现有的标准数据类型(这与编写库方法非常相似,但在这种情况下,数据类型是原始的而不是用户定义的。我们需要编写JavaScript String假设功能名称swapCase()。
此函数将返回一个新的字符串,其中所有大写字符都被替换为小写字符,反之亦然。任何非字母字符都应保持原样。
示例
以下是代码-
const str = 'ThIS iS A CraZY StRInG';
String.prototype.swapCase = function(){
let res = '';
for(let i = 0; i < this.length; i++){
if(this[i].toLowerCase() === this[i].toUpperCase()){
res += this[i];
continue;
};
if(this[i].toLowerCase() === this[i]){
res += this[i].toUpperCase();
continue;
};
res += this[i].toLowerCase();
};
return res;
};
console.log(str.swapCase());
输出结果
以下是控制台中的输出-
tHis Is a cRAzy sTriNg






