let output ="I am a string"
const app=output.split("")
console.log(app)
//output (13) [ "I", " ", "a", "m", " ", "a", " ", "s", "t", "r", "i", "n", "g" ]
then it need to change per letter into the next one in alphabetically
which means
"j","","b","n","","b,","","t","u","s","j","o","h"
after that the string must be written like ; "jbnbtusjoh"
any opinion?
CodePudding user response:
Ok, so lets do this step by step:
// first the string
let out = "I am a string"
// convert to array
let arOut = out.split("") // gives ["I"," ", "a", "m", " ", "a"....]
// now lets get cracking :
let mapped = arOut.map(element => element == ' ' ? element : String.fromCharCode(element.charCodeAt(0) 1))
// this get char code of element and then adds one and gets equivalent char ignores space
let newOut = mapped.join("") // we have our result
console.log(newOut)
CodePudding user response:
After splitting, map the array of characters, convert each one to code (if not a space), add one, and convert the code back to a char:
const output = 'I am a string'
const result = output.split('')
.map(c => c === ' '
? c // ignore spaces
: String.fromCharCode(c.charCodeAt(0) 1) // convert char to code, add one, and convert back to char
)
.join('') // if you need a string
console.log(result)
You can also use Array.from()
to directly convert the string to an array of the transformed characters:
const output = 'I am a string'
const result = Array.from(
output,
c => c === ' ' ? c : String.fromCharCode(c.charCodeAt(0) 1)
).join('')
console.log(result)
CodePudding user response:
Why not convert each char into ASCII and then simply increment the number?