Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第5天 写一个把字符串大小写切换的方法 #15

Open
haizhilin2013 opened this issue Apr 20, 2019 · 82 comments
Open

[js] 第5天 写一个把字符串大小写切换的方法 #15

haizhilin2013 opened this issue Apr 20, 2019 · 82 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第5天 写一个把字符串大小写切换的方法

@haizhilin2013 haizhilin2013 added the js JavaScript label Apr 20, 2019
@undefinedYu
Copy link
Contributor

var reversal = function(str){
var newStr = '';
if(Object.prototype.toString.call(str).slice(8,-1) !== 'String'){
alert("请填写字符串")
}else{
for(var i=0;i<str.length;i++){
newStr += ((str.charCodeAt(i)>96 && str.substr(i,1).toUpperCase()) || str.substr(i,1).toLowerCase());
}
}
return newStr;
}

@linghucq1
Copy link

linghucq1 commented May 8, 2019

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 

@lantian1024
Copy link

lantian1024 commented May 15, 2019

function caseConvert(str){
    return str.replace(/([a-z]*)([A-Z]*)/g, (m, s1, s2)=>{
	return `${s1.toUpperCase()}${s2.toLowerCase()}`
    })
}
caseConvert('AsA33322A2aa') //aSa33322a2AA

@fuiiiiiii
Copy link

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

@likeke1997
Copy link

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

@MartinsYong
Copy link

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;
}

@Konata9
Copy link

Konata9 commented Jul 2, 2019

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'))

@Azathoth-H
Copy link

const upperOrlower = (str) => str.split('').reduce((acc, x)=> acc+= x == x.toLocaleUpperCase()? x.toLocaleLowerCase(): x.toLocaleUpperCase(), '')
    upperOrlower("what's THIS ?") // WHAT'S this ?

@seho-dev
Copy link

学习到了,借鉴到了;

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"));

@shufangyi
Copy link

const exchangeUpAndLow = str =>
  typeof str === 'string'
    ? str.replace(/[A-Za-z]/g, char =>
        char.charCodeAt(0) <= 90
          ? char.toLocaleLowerCase()
          : char.toLocaleUpperCase()
      )
    : str

@wyx2014
Copy link

wyx2014 commented Jul 24, 2019

function change2Char(str) {
  if(typeof str !== 'string'){
    return '请输入字符串';
   }
   return str.split('').map(function (item) {
       return /^[a-z]$/.test(item)?item.toUpperCase():item.toLowerCase();
   }).join('');

@gu-xionghong
Copy link

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')

@IanSun
Copy link

IanSun commented Jul 26, 2019

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,
    ``,
  );
}

@wsb260
Copy link

wsb260 commented Jul 31, 2019

// 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

@lkkwxy
Copy link

lkkwxy commented Aug 20, 2019

  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
          }
        }, "")
      }

@J1nvey
Copy link

J1nvey commented Sep 3, 2019

const change = str => {
    return [...str].map( letter => {
        return letter.toLowerCase() === letter ?
            letter.toUpperCase() : letter.toLowerCase();
    }).join("");
}
console.log(change("abd  ADSas")); // ABD  adsAS

刚开始没看清楚题,以为全大写全小写....

@JJL-SH
Copy link

JJL-SH commented Sep 5, 2019

function stringToUpperLower(str) {
  return str.replace(/([a-z]*)([A-Z]*)/g, (all, $1, $2) => {
    return $1.toUpperCase() + $2.toLowerCase();
  })
}
console.log(stringToUpperLower('a0B1c2D3e4F5g'))

@yaoyujian
Copy link

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

@ZindexYG
Copy link

function sonversion (str) {
  return str.replace(/([A-Z]*)([a-z]*)/g,(match,$1,$2)=>{
    return `${$1.toLowerCase()}${$2.toUpperCase()}`
  })
}

console.log(sonversion('aaBBCCdd'))

@vanstline
Copy link

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
}

@klren0312
Copy link

'aAc3_DD=sdLL'.replace(/([a-z]|[A-Z])/g, v => v.toLowerCase() === v ? v.toUpperCase() : v.toLowerCase())

@tianfeng65
Copy link

/**
 * 写一个把字符串大小写切换的方法
 * @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"

@weizhanzhan
Copy link

function convertCase(str){
  return str.split('').map(s=>s===s.toUpperCase()? s.toLowerCase():s.toUpperCase()).join('')
}
convertCase('aSd')  //AsD

@diandianzd
Copy link

diandianzd commented Oct 12, 2019

function convertStr(str) {
  return [...str].map(char => char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase()).join('')
}

console.log(convertStr('aBc'))
// AbC

@0x3c
Copy link

0x3c commented Oct 15, 2019

/**
 * @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;
}

@13714273163
Copy link

  function changeStr(str = 'abcQWE') {
        return str.split('').map(item => {
            return /[a-z]/.test(item) ? item.toUpperCase() : item.toLocaleLowerCase()
        }).join('')
    }

@crazyming9528
Copy link

function caseConvert(str) {
return str.replace(/([a-z])([A-Z])/g, function (str, sub1, sub2) {
return sub1.toLocaleUpperCase() + sub2.toLocaleLowerCase();
})

@YeChang
Copy link

YeChang commented Dec 22, 2019

//第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));

@kruzabc
Copy link

kruzabc commented Dec 23, 2019

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效果好。

@378406712
Copy link

const switchStr = (str) => {
let arr = [];
for (let i of str) {
const index = i.charCodeAt();
if (index >= 65 && index <= 90) {
arr.push(i.toLowerCase());
} else if (index >= 97 && index <= 122) {
arr.push(i.toUpperCase());
}
else{
arr.push(i)
}
}
return arr.join("");
};

@cielaber
Copy link

function stringCaseSwitch(str){
let tempArr = [];
for(let i = 0;i<str.length;i++){
if(str.charCodeAt(i)>=65 && str.charCodeAt(i)<=90){
tempArr.push(str[i].toLowerCase())
}else if(str.charCodeAt(i)>=97 && str.charCodeAt(i)<=122){
tempArr.push(str[i].toUpperCase())
}else{
tempArr.push(str[i])
}
}
return tempArr.join('');
}

@TonyGoods
Copy link

function func(str){
return str.split("").reduce((prev,curr)=>prev+(curr>='a'?curr.toUpperCase():curr.toLowerCase()),'')}

@TanyaTl
Copy link

TanyaTl commented May 12, 2021

function translateAa(str) {
//拆分字符串为数组
var temp = str.split('');
var m = "";
temp.map(s => {
if (s.charCodeAt(0) >= 65 && s.charCodeAt(0) <= 90) {
console.log(s.charCodeAt(0) + 32);
s = s.toLowerCase();

        } else if (s.charCodeAt(0) >= 97 && s.charCodeAt(0) <= 122) {
            s = s.toUpperCase();
        }
        m += s;
    })
    return m;
}
console.log("abBB   __Abjn");
console.log(translateAa("abBB   __Abjn"));

@4479zheng
Copy link

function toggleCase(str){
let arr = str.split('');
for(let i = 0; i < arr.length; i++) {
if(arr[i].charCodeAt() > 65 && arr[i].charCodeAt() < 90) {
arr[i] = arr[i].toLowerCase();
}else if(arr[i].charCodeAt() > 97 && arr[i].charCodeAt() < 122) {
arr[i] = arr[i].toUpperCase();
}
}
str = arr.join('');
return str;
}
toggleCase('he_wolE_d');

@youyanhui
Copy link

<script type="text/javascript"> function changStr(str){ if(typeof str !== 'string'){ console.log('确认要更改的对象是字符串') }else{ let newName='' let arr = str.split('') arr.forEach(e=>{ let code = e.charCodeAt() // A~Z 65~90 a~z 97~122 大小写字母的ASCII码 if((code>=65&&code<=90)||(code>=97&&code<=122)){ newName += (code>96 ? e.substr(0,1).toUpperCase(): e.substr(0,1).toLowerCase()) }else{ newName += e } }) return newName } } const str = changStr('ab-FD') console.log(str) </script>

@xuan-123
Copy link

var str = 'abcdeFGHIJKLmnopqRSTUVwxyz'
function toCase(){
return str.split('').map(
item=>{
if(item.charCodeAt() <= 90){
return item.toLocaleLowerCase()
}else{
return item.toUpperCase()
}
}
).join('')
}

@amikly
Copy link

amikly commented Oct 23, 2021

  //  Unicode编码 A(65) - Z(90) a(97) - b(122)
  function toggleCase(str) {
    return str
      .split("")
      .map((char) => {
        if (char.charCodeAt() >= 65 && char.charCodeAt() <= 90) {
          return char.toLowerCase();
        } else if (char.charCodeAt() >= 97 && char.charCodeAt() <= 122) {
          return char.toUpperCase();
        }
      })
      .join("");
  }
  console.log(toggleCase("sdiawhiAAsfFFDD"));

@VaynePeng
Copy link

function caseConvert(str) {
  return str.replace(/([a-z]+)|([A-Z]+)/g, (match, $1, $2) => {
    return $1 ? $1.toUpperCase() : $2.toLowerCase()
  })
}
caseConvert('aBZc')

@July107
Copy link

July107 commented Nov 2, 2021

const changeCase = (str) => {
    return str
            .split('')
            .map((s) => (/[A-Z]/.test(s) ? s.toLowerCase() : s.toUpperCase()))
            .join('');
}

console.log(changeCase('AbCdEfG'));
console.log(changeCase('AAAAAAbbbbbbcccccDDDDDDeeeeeFFFFF'));

@tk12138
Copy link

tk12138 commented Nov 7, 2021

let mystr = 'nidHDIEkdIEDN'
function toggle(str) {
let newArr = []
for (var index in str) {
var num = str[index]
if(num.charCodeAt(0) > 97){
num = num.toUpperCase()
}else{
num = num.toLowerCase()
}
newArr.push(num)
}
return newArr.join('')
}

console.log(toggle(mystr))

@QiaoIsMySky
Copy link

    function toChange(str) {
        let strArr = str.split('')
        strArr.forEach((i, index) => {
            if (i.charCodeAt() >= 97 && i.charCodeAt() <= 122) {
                strArr[index] = i.toUpperCase()
            } else if (i.charCodeAt() >= 65 && i.charCodeAt() <= 90){
                strArr[index] = i.toLowerCase()
            }
        })
        return strArr.join('')
    }

@JackTam1993
Copy link

JackTam1993 commented Feb 8, 2022 via email

@github-cxtan
Copy link

function UpcaseSwitchLowcase(data){
let array = data.split('');
for (let index = 0; index < array.length; index++) {
if (array[index].charCodeAt(0) <= 90 && array[index].charCodeAt(0) >= 65){
array[index] = array[index].toLowerCase();
}else if (array[index].charCodeAt(0) <= 122 && array[index].charCodeAt(0) >= 97){
array[index] = array[index].toUpperCase();
}
}
return array.join('');
}

@github-cxtan
Copy link

function UpcaseSwitchLowcaseMap(data){
return data.split('').map(e =>{
if (e.charCodeAt(0) <= 90 && e.charCodeAt(0) >= 65){
return e.toLowerCase();
}else if (e.charCodeAt(0) <= 122 && e.charCodeAt(0) >= 97){
return e.toUpperCase();
}
}).join('');
}

@yxllovewq
Copy link

const changeCase = (str = '', type = false) => {
let arr =str.split('');
if (type === true) {
str = arr.map(v => v.toUpperCase()).join('');
}
else {
str = arr.map(v => v.toLowerCase()).join('');
}
return str;
}

@JackTam1993
Copy link

JackTam1993 commented Mar 8, 2022 via email

@bia2000
Copy link

bia2000 commented Apr 29, 2022

第5天 写一个把字符串大小写切换的方法
function change(value) {
let result = ''
for (let item of value) {
let code = item.charCodeAt()
if (code > 97) {
result += String.fromCharCode(code - 32)
}
else
result += String.fromCharCode(code + 32)
}
return result;
}
console.log(change('dfssd'));

@lxt-ing
Copy link

lxt-ing commented Apr 29, 2022 via email

@vesere
Copy link

vesere commented May 15, 2022

var str = 'zyytNhCXzwsb'

var arr = []

function tpup(str){
const newArr = str.split('')
newArr.forEach(item=>{
if(item===item.toUpperCase()) {
item = item.toLowerCase()
}else{
item = item.toUpperCase()
console.log(item);
}
arr.push(item)
})
return arr.join('')
}

console.log(tpup(str)); // ZYYTnHcxZWSB

@xiaoqiangz
Copy link

// 切换大小写子母
function changeStr(str) {
let arr = str.split('')
return arr.map(code => {
// return code.charCodeAt() <= 90 ? code.toLowerCase() : code.toUpperCase()
return /[A-Z]/.test(code) ? code.toLowerCase() : code.toUpperCase()
}).join('')
}
console.log(changeStr("what's THIS ?"))

@JackTam1993
Copy link

JackTam1993 commented May 22, 2022 via email

@www-wanglong
Copy link

'asdaASDsda'.replace(/([a-z])([A-Z])/g, (match, $1, $2) => $1.toUpperCase() + $2.toLowerCase() )

@JackTam1993
Copy link

JackTam1993 commented Jun 18, 2022 via email

@wyy-g
Copy link

wyy-g commented Sep 7, 2022

function change(str){
var arr = str.split('');
return arr.map(item => {
return item.charCodeAt() >= 97 ? item.toUpperCase() : item.toLowerCase();
}).join('');
}

@JackTam1993
Copy link

JackTam1993 commented Sep 7, 2022 via email

1 similar comment
@JackTam1993
Copy link

JackTam1993 commented Oct 11, 2022 via email

@Hanies11
Copy link

function fun(str) {
    let newStr = '';
    for (let i = 0; i < str.length; i++) {
        let codeAt = str[i].charCodeAt();
        if (codeAt >= 65 && codeAt <= 90) {
            newStr += str[i].toLowerCase();
        } else if (codeAt >= 97 && codeAt <= 122) {
            newStr += str[i].toUpperCase();
        } else {
            newStr += str[i];
        }
    }
    return newStr
}
console.log(fun("aQWfsdaxOOODFSsdsd"))

@JackTam1993
Copy link

JackTam1993 commented Mar 12, 2023 via email

@lili-0923
Copy link

let arr =[];
for (let item of str){
if(item === item.toUpperCase()){
item = item.toLowerCase();
}else{
item = item.toUpperCase();
}
arr.push(item)
}
let newArr = arr.join('');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests