字符串反转 因为这个是用的自己的最简单的方法进行的实现,所以不整理代码了 回文(正着读与反着读效果一样,称为回文) 思路:利用数组的reverse方法,join方法进行拼接,判断反转后拼接是否与原数据一致,一致则是回文 出现次数最多的字符 思路:创建一个对象,然后遍历字符串,字符串的每个字符作为对象的key,value是对应该字符出现的次数。然后我们可以遍历这个对象,找出value最大的key
const maxCharacter = (str) => {
const obj = {}
let max = 0
let character = ''
for (let index in str) {
obj[str[index]] = obj[str[index]] + 1 || 1
}
for (let i in obj) {
if (obj[i] > max) {
max = obj[i]
character = i
}
}
return character
}
找出string中元音字母出现的个数 思路:利用正则表达式提取所有的元音,然后统计。利用数组的includes方法,但是首先输入的参数转为小写
const vowels = str => {
const choices = ['a', 'e', 'i', 'o', 'u']
let count = 0
for (let character in str) {
if (choices.includes(str[character])) {
count ++
}
}
return count
}
//match 返回的是字符串类型,返回匹配到的信息内容
const vowelsRegs = str => {
const match = str.match(/[aeiou]/gi)
return match ? match.length : 0
}
数组分隔 思路:通过熟路的slice进行截取,利用while进行循环按给定大小的步骤递增
const chunk = (array, size) => {
const chunks = []
let index = 0
while(index < array.length) {
chunks.push(array.slice(index, index + size))
index += size
}
return chunks
}
首字母大写 思路:指定位置的字符进行大写,然后拼接截取指定位置开始的剩余的字符
const capitalize = str => {
return str.split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ')}
凯撒密码(百度具体意思)
const caesarCipher = (str, number) => {
const alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
const string = str.toLowerCase()
const remainder = number % 26
let outPut = ''
for (let i = 0; i < string.length; i++) {
const letter = string[i]
if (!alphabet.includes(letter)) {
outPut += letter
} else {
let index = alphabet.indexOf(letter) + remainder
if (index > 25) {
index -= 26
}
if (index < 0) {
index += 26
}
outPut += str[i] === str[i].toUpperCase() ? alphabet[index].toUpperCase() : alphabet[index]
}
}
return outPut
}