第五天
Javascript题目
题目 : 写一个把字符串大小写切换的方法(js)
问题解答
解题思路
正则
// 写一个把字符串大小写切换的方法function caseConvert(str) { return str.replace(/([a-z]*)([A-Z]*)/g, (m, s1, s2) => { return `${s1.toUpperCase()}${s2.toLowerCase()}` })}console.log(aseConvert('AsA33322A2aa')) //aSa33322a2AA
for…of方法
let arr = []function toChange(str) { for (let item of str) { //不严谨 如果出现其他字符串 极可能出问题 // item = item === item.toUpperCase() itetoLowerCase() : item.toUpperCase() let newStr = '' if (item === item.toUpperCase()) { item = item.toLowerCase() newStr += item.toLowerCase() } else if (item === item.toLowerCase()) { item = item.toUpperCase() newStr += } else {} arr.push(item) } return arr.join('')}console.log(toChange('aBc_D1e2FgH')) //AbC_d1E2fGh
charCodeAt和fromCharCode方法
- 这里可以使用 遍历方法 将值多次进行转换, 下面使用的是数值pull后将数据一次的进行转换
let arr = []function toChange(str) { for (let item of str) { const i = item.charCodeAt() if (i > 65 && i < 90) { i + 32; // item = String.fromCharCode(i) } else if (i > 90 && i < 122) { i - 32; } else {} arr.push(i) //arr.push(item) } return String.fromCharCode.apply(null, arr) //arr.join('')}console.log(toChange('aBc_D1e2FgH')) //AbC_d1E2fGh
扩展
toUpperCase的意思是将所有的英文字符转换为大写字母toLowerCase的意思是将所有的英文字符转换为小写字母for...of 可以直接遍历 数组 , 字符串 , arguments , 集合 等等, 在of之前还可以使用解构语法- 使用
for…in遍历数组, 我们得到的是结果是数组的下标, 而想要得到数组本身的值, 则可以使用a[i](for…of)这样的方式 String.fromCharCode() 可接受一个指定的 Unicode 值, 然后返回一个字符串. 在传递多个动态变量时 可以使用 String.fromCharCode.apply(null, array)的方法charCodeAt(index) 方法可返回指定位置的字符的 Unicode 编码. 这个返回值是 0 - 65535 之间的整数.