字符串加密

链接:字符串加密 Encrypt this!

Rules:

  • The first letter needs to be converted to its ASCII code.
  • The second letter needs to be switched with the last letter

Examples:

encryptThis(“Hello”) === “72olle”
encryptThis(“good”) === “103doo”
encryptThis(“hello world”) === “104olle 119drlo”

加密字符串:字符串的第一个字母转为ASCII码,第二个字母与最后一个字母交换。

解法1:利用Array.prototype.slice截取字符串的字符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var encryptThis = function(text) {
let arr = text.split(' ').map(function(item){
if(item.length==1){
return item.charCodeAt(0)
}
else if(item.length==2){
return item.charCodeAt(0)+item.slice(1)
}
else if(item.length>=3){
return item.charCodeAt(0)+item.slice(-1)+item.slice(2,-1)+item[1]
}
})
return arr.join(" ")
}

解法2:利用正则表达式。

1
2
3
4
5
6
7
const encryptThis = text => text
.split(' ')
.map(word => word
.replace(/(^\w)(\w)(\w*)(\w$)/, `$1$4$3$2`)
.replace(/^\w/, word.charCodeAt(0))
)
.join(' ');
Contents
  1. 1. Rules:
  2. 2. Examples:
|