How can I convert a string to numeric values (should be reversible) using JavaScript?

前端 未结 2 774
不知归路
不知归路 2021-01-15 12:36

How can I convert a JavaScript string into a unique numeric value such that you can convert the numeric value back to the string? The length of the numeric value doesn\'t ma

2条回答
  •  無奈伤痛
    2021-01-15 13:18

    Strings are actually stored as numbers. We can get the ascii code for each letter in the string and concat them into one big number forcing each number to be three digits so we can easily reverse the process.

    function convertToNumber(str){
      var number = "";
      for (var i=0; i

    Now we can take this long number and turn it back into a string by pulling the numbers off three at a time and using the opposite of char.charCodeAt(0) which is String.fromCharCode(num):

    function convertToString(numbers){
      origString = "";
      numbers = numbers.match(/.{3}/g);
      for(var i=0; i < numbers.length; i++){
        origString += String.fromCharCode(numbers[i]);
      }
      return origString;
    }
    alert(convertToString("083079032100111101115032109121032104111109101119111114107"));  //console.log is better
    

提交回复
热议问题