如何在使用charCodeAt和charCodeFrom时删除空格?

时间:2017-09-11 13:34:22

标签: javascript

此函数包含一个ROT13密码,它首先拆分提供的字符串并将值移动13。唯一的问题是它在返回时包含单词之间的短划线,我不知道如何解决该问题。

function rot13(str) { 

var strSplit = str.split('');
var strMap = strSplit.map(function(x) {
return (x.charCodeAt(0) + 13 - 65) % 26 + 65;
}); 

return String.fromCharCode.apply(this, strMap);
}


rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.");

1 个答案:

答案 0 :(得分:1)

检查当前字符是否为空格。如果是,请返回。否则,移动值:



function rot13(str) {

  var strSplit = str.split('');
  var strMap = strSplit.map(function(x) {
    return x === ' '                           // Is it a space?
      ? x.charCodeAt(0)                        // Then return the space
      : (x.charCodeAt(0) + 13 - 65) % 26 + 65; // If not, then apply the shift.
  });

  return String.fromCharCode.apply(this, strMap);
}


console.log(rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK."));




或者,更好的是,只移动你想要的字符:



function rot13(str) {

  var strSplit = str.split('');
  var strMap = strSplit.map(function(x) {
    return /[a-zA-Z]/.test(x)                 // Is it a letter?
      ? (x.charCodeAt(0) + 13 - 65) % 26 + 65 // Shift it! 
      : x.charCodeAt(0)                       // Otherwise, return the not-letter.
  });

  return String.fromCharCode.apply(this, strMap);
}


console.log(rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK."));