第5天 写一个把字符串大小写切换的方法
var reversal = function(str){
var newStr = '';
if(Object.prototype.toString.call(str).slice(8,-1) !== 'String'){
alert("请填写字符串")
}else{
for(var i=0;i
}
}
return newStr;
}
function caseConvert(str) {
return str.split('').map(s => {
const code = s.charCodeAt();
if (code < 65 || code > 122 || code > 90 && code < 97) return s;
if (code <= 90) {
return String.fromCharCode(code + 32)
} else {
return String.fromCharCode(code - 32)
}
}).join('')
}
console.log(caseConvert('AbCdE')) // aBcDe
function caseConvertEasy(str) {
return str.split('').map(s => {
if (s.charCodeAt() <= 90) {
return s.toLowerCase()
}
return s.toUpperCase()
}).join('')
}
console.log(caseConvertEasy('AbCxYz')) // aBcXyZ
function caseConvert(str){
return str.replace(/([a-z]*)([A-Z]*)/g, (m, s1, s2)=>{
return `${s1.toUpperCase()}${s2.toLowerCase()}`
})
}
caseConvert('AsA33322A2aa') //aSa33322a2AA
let str = 'aBcDeFgH'
let arr = []
for(let item of str) {
if (item === item.toUpperCase()) {
item = item.toLowerCase()
} else {
item = item.toUpperCase()
}
arr.push(item)
}
let newStr = arr.join('')
console.log(newStr)
// AbCdEfGh
function toggle(str) {
var result = str.split('');
result.forEach(function(e, i, a) {
a[i] = e === e.toUpperCase() ? a[i] = a[i].toLowerCase() : a[i] = a[i].toUpperCase()
});
return result.join('');
}
var result = toggle('ifYouAreMyWorld');
console.log(result); // IFyOUaREmYwORLD
function caseTransform (str) {
let transformed = '';
for (let v of str) {
const charCode = v.charCodeAt();
if (charCode >= 97 && charCode <= 122) {
transformed += v.toUpperCase();
}
else if (charCode >= 65 && charCode <= 90) {
transformed += v.toLowerCase();
}
else {
transformed += v;
}
}
return transformed;
}
const convertCase = (str) =>
str
.split("")
.map((s) => (/[A-Z]/.test(s) ? s.toLowerCase() : s.toUpperCase()))
.join("");
console.log(convertCase('AbCdE'))
console.log(convertCase('aaabbbCCCDDDeeefff'))
console.log(convertCase('aBcDe'))
const upperOrlower = (str) => str.split('').reduce((acc, x)=> acc+= x == x.toLocaleUpperCase()? x.toLocaleLowerCase(): x.toLocaleUpperCase(), '')
upperOrlower("what's THIS ?") // WHAT'S this ?
学习到了,借鉴到了;
function test(str) {
return str.replace(/([a-z])([A-Z])/g, (m, s1, s2) => {
return ${s1.toUpperCase()}${s2.toLowerCase()}
;
});
}
function test2(str) {
let arr = [];
for (let x of str) {
if (x === x.toUpperCase()) {
x = x.toLowerCase();
} else {
x = x.toUpperCase();
}
arr.push(x);
}
return arr.join("");
}
console.log(test("a6M3cH"));
const exchangeUpAndLow = str =>
typeof str === 'string'
? str.replace(/[A-Za-z]/g, char =>
char.charCodeAt(0) <= 90
? char.toLocaleLowerCase()
: char.toLocaleUpperCase()
)
: str
function change2Char(str) { if(typeof str !== 'string'){ return '请输入字符串'; } return str.split('').map(function (item) { return /^[a-z]$/.test(item)?item.toUpperCase():item.toLowerCase(); }).join('');
function caseConvert(str) {
return str.replace(/([a-z])?([A-Z]?)/g, function(m, $1, $2) {
let s = ''
s += $1 ? $1.toUpperCase() : ''
s += $2 ? $2.toLowerCase() : ''
return s
})
}
caseConvert('asd__BBB_cDe')
function reverseCharCase ( string = `` ) {
return Array.prototype.reduce.call(
string,
( string, char ) =>
string += `\u0040` < char && `\u005b` > char ?
char.toLowerCase() :
`\u0060` < char && `\u007b` > char ?
char.toUpperCase() :
char,
``,
);
}
// 1.test() 方法用于检测一个字符串是否匹配某个模式,返回Boolean值
// 2.toUpperCase() 转换成大写,toLowerCase()转换成小写
function changeStr(str){
let ary = [];
let newStr = '';
if(!str||str === ''||typeof str !== 'string'){
return false;
}
ary = str.split("");
ary.map(item => {
newStr += /[A-Z]/.test(item) ? item.toLowerCase() : item.toUpperCase();
})
console.log(newStr)
}
changeStr('aAbBcC') // 输出:AaBbCb
//$1、$2、...、$99与 regexp 中的第 1 到第 99 个子表达式相匹配的文本
//function(a,b,c)一共可以传入3个参数,第一个为匹配到的字符串,第二个为匹配字符串的起始位置,第三个为调用replace方法的字符串本身,(非全局匹配的情况下/g),下例为多组匹配,s1,s2分别对应$1,$2
function caseConvert(str){
return str.replace(/([a-z]*)([A-Z]*)/g, function(m,s1,s2){
return s1.toUpperCase() + s2.toLowerCase()
})
}
console.log(caseConvert('aSa')) //AsA
function caseConvert(sourceString) {
if (typeof sourceString !== "string") {
return ""
}
return sourceString.split("").reduce((previousValue, currentValue) => {
let charCode = currentValue.charCodeAt()
if (
(charCode >= 65 && charCode <= 90) ||
(charCode >= 97 && charCode <= 122)
) {
if (charCode <= 90) {
return previousValue + String.fromCharCode(charCode + 32)
} else {
return previousValue + String.fromCharCode(charCode - 32)
}
} else {
return previousValue + currentValue
}
}, "")
}
const change = str => {
return [...str].map( letter => {
return letter.toLowerCase() === letter ?
letter.toUpperCase() : letter.toLowerCase();
}).join("");
}
console.log(change("abd ADSas")); // ABD adsAS
刚开始没看清楚题,以为全大写全小写....
function stringToUpperLower(str) {
return str.replace(/([a-z]*)([A-Z]*)/g, (all, $1, $2) => {
return $1.toUpperCase() + $2.toLowerCase();
})
}
console.log(stringToUpperLower('a0B1c2D3e4F5g'))
let str='aAc3_DD=sdLL'
function tolawe(params) {
return str.replace(/[a-zA-Z]/g,word=>{
let patt1 = new RegExp("[a-z]",'g');
if(patt1.test(word)){
return word.toUpperCase()
}
else{
return word.toLowerCase()
}
})
}
let newstr=tolawe(str)
console.log(newstr)//AaC3_dd=SDll
function sonversion (str) {
return str.replace(/([A-Z]*)([a-z]*)/g,(match,$1,$2)=>{
return `${$1.toLowerCase()}${$2.toUpperCase()}`
})
}
console.log(sonversion('aaBBCCdd'))
function transUppLow(str) {
if(typeof str !== 'string') {
alert('请输入string类型')
}
var arr = str.split('')
var newStr = ''
arr.forEach(s => {
s = s.toUpperCase() !== s ? s.toUpperCase() : s.toLowerCase()
newStr+= s
});
return newStr
}
'aAc3_DD=sdLL'.replace(/([a-z]|[A-Z])/g, v => v.toLowerCase() === v ? v.toUpperCase() : v.toLowerCase())
/**
* 写一个把字符串大小写切换的方法
* @param {String} str
*/
function toggleCase(str) {
return str
.split("")
.map(item => /[A-Z]/.test(item) ? item.toLocaleLowerCase() : item.toLocaleUpperCase())
.join("");
}
console.log(toggleCase("aa+-12BB")); // "AA+-12bb"
function convertCase(str){
return str.split('').map(s=>s===s.toUpperCase()? s.toLowerCase():s.toUpperCase()).join('')
}
convertCase('aSd') //AsD
function convertStr(str) {
return [...str].map(char => char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase()).join('')
}
console.log(convertStr('aBc'))
// AbC
/**
* @param {string} str
* @return {string}
*/
function convert(str) {
var res = "";
for (var chr of str) {
var code = chr.charCodeAt();
if (code >= 65 && code <= 90) {
code += 32;
} else if (code >= 97 && code <= 122) {
code -= 32;
} else {
}
res += String.fromCharCode(code);
}
return res;
}
function changeStr(str = 'abcQWE') {
return str.split('').map(item => {
return /[a-z]/.test(item) ? item.toUpperCase() : item.toLocaleLowerCase()
}).join('')
}
function caseConvert(str) {
return str.replace(/([a-z])([A-Z])/g, function (str, sub1, sub2) {
return sub1.toLocaleUpperCase() + sub2.toLocaleLowerCase();
})
//第5天 写一个把字符串大小写切换的方法
//for example: aBcDeFg => AbCdEfG
//"a".charCodeAt(0) 97
//"A".charCodeAt(0) 65
function toggleCase(str) {
return str
.split("")
.map(c => {
return c.charCodeAt(0) >= 97 ? c.toUpperCase() : c.toLowerCase();
})
.join("");
}
var str = "aBcDeFg";
console.log(toggleCase(str));
function sonversion (str) { return str.replace(/([A-Z]*)([a-z]*)/g,(match,$1,$2)=>{ return `${$1.toLowerCase()}${$2.toUpperCase()}` }) } console.log(sonversion('aaBBCCdd'))
如果用正则的话,这个比较好function函数被调用的次数要少。上面有个正则是 /([A-Z]?)([a-z]?)/g
, 没有你这个/([A-Z]*)([a-z]*)/g
效果好。
````js
function fun(str) {
let newStr = ''
for (let i = 0; i < str.length; i++) {
let newStr1 = str.substring(i, i + 1)
if (newStr1 < 'A' || newStr1 > 'Z') {
newStr += newStr1.toUpperCase()
} else {
newStr += newStr1.toLowerCase()
}
}
return newStr
}
console.log(fun('AbCdefgASDASDsAASDq uyqwugf'))
var str = "aVcDdaAB";
function change(str){
var newStr="";
for(var i=0;i<str.length;i++){
if(str[i].toUpperCase()===str[i]){
newStr+=str[i].toLowerCase();
}else{
newStr+=str[i].toUpperCase();
}
};
return newStr;
};
change(str);
const toggleCase1 = (str) => {
return str.replace(/([a-z]*)([A-Z]*)/g,(m,$1,$2) => {
return $1.toUpperCase()+$2.toLowerCase()
})
}
const toggleCase2 = (str) => {
return str.split('').map((val) => {
return /[a-z]/.test(val)?val.toUpperCase() : val.toLowerCase()
}).join('')
}
function transform (str) {
return str.split('').map(item => {
let code = item.charCodeAt()
if (64 < code && code < 91) return item.toLowerCase()
if (96 < code && code < 123) return item.toUpperCase()
return item
}).join('')
}
console.log(transform('AAZZaazz'))
不知道审题是否正确,下面是一个将字符串中的大小写反转的方法。
即原来小写变大写,原来大写变小写。
var str = '$a1a2a_B3B4B$';
function transformCode(code) {
return code.replace(/([A-Z])|([a-z])/g, function(match, $1, $2) {
if ($1) {
return $1.toLowerCase();
} else if ($2) {
return $2.toUpperCase();
}
});
}
function switchCase(str) {
function handleSwitch(match) {
return match.toUpperCase() === match ? match.toLowerCase() : match.toUpperCase()
}
return str.replace(/[A-Za-z]/g, handleSwitch)
}
console.log(switchCase('aBCDefg')) // AbcdEFG
[...str].map((value) => {
return value.match(/[A-Z]1?/g) ? value.toLowerCase() : value.toUpperCase()
}).join('')
function changeLetterCase(str){
if(typeof str !== 'string'){
return
}
return str.replace(/([a-z])|([A-Z])/g, (target, s1, s2) => {
if(s1){
return s1.toUpperCase()
}else if(s2){
return s2.toLowerCase()
}else {
return ''
}
})
}
function strToCamel(str) {
return str.replace(/[a-zA-Z]/g, item => item.charCodeAt(0) < 97 ? item.toLowerCase() : item.toUpperCase());
}
const convertCase = (str = "") =>
[...str].reduce((pre, cur) => {
cur = /[A-Z]/.test(cur) ? cur.toLowerCase() : cur.toUpperCase();
return pre + cur;
}, "");
convertCase("AbCdE"); // "aBcDe"
function fn(str) {
var newstr = '';
for (let item of str) {
if (item == item.toUpperCase()) {
item = item.toLowerCase();
newstr += item;
} else {
item = item.toUpperCase();
newstr += item;
}
}
return newstr;
}
function caseConvert(str,type){
let formatterStr = '';
switch(type){
case 'up':
formatterStr = str.replace(/[a-z]/g,(char)=>char.toUpperCase())
break;
case 'low':
formatterStr = str.replace(/[A-Z]/g,(char)=>char.toLowerCase())
}
return formatterStr;
}
var finalStr = "";
for(var i = 0; str && i < str.length; i++) {
finalStr += str[i] === str[i].toUpperCase() ? str[i].toLowerCase() : str[i].toUpperCase();
}
`function caseConvert(str) {
return str.split('').map(s => {
const code = s.charCodeAt();
if (code < 65 || code > 122 || code > 90 && code < 97) return s;
if (code <= 90) {
return String.fromCharCode(code + 32)
} else {
return String.fromCharCode(code - 32)
}
}).join('')
}
console.log(caseConvert('AbCdE')) // aBcDe
function caseConvertEasy(str) {
return str.split('').map(s => {
if (s.charCodeAt() <= 90) {
return s.toLowerCase()
}
return s.toUpperCase()
}).join('')
}
console.log(caseConvertEasy('AbCxYz')) // aBcXyZ `
function reverseCharCase(str) {
if (!(typeof str === 'string')) {
throw new Error('str must be string');
}
// 如果是空字符串,直接返回
if (!str.length) {
return str;
}
const lowerCaseReg = /[a-z]/;
const upperCaseReg = /[A-Z]/;
const len = str.length;
let i = 0;
let result = '';
while(i < len) {
if (lowerCaseReg.test(str.charAt(i))) {
result += str.charAt(i).toLocaleUpperCase();
} else if (upperCaseReg.test(str.charAt(i))) {
result += str.charAt(i).toLocaleLowerCase();
} else {
result += str.charAt(i);
}
i++;
}
return result;
}
const testStringArray = ['', '1a1', 'aABz', 'aC R + 6788978e892*&&*(^%&*%^&%^&e'];
testStringArray.forEach(str => {
console.log(reverseCharCase(str));
});
lowerSwapUpper = str => str.replace(/([A-Z])([a-z])/g,(_,$1,$2) => $1.toLowerCase()+$2.toUpperCase());
function upperCaseSwitch(str) {
let strArr = [...str];
let newArr = strArr.map(item => item.charCodeAt() >= 97 ? item.toUpperCase() : item.toLowerCase())
return newArr.join('');
}
Most helpful comment