将数字转换为字母

时间:2011-01-13 16:32:22

标签: javascript

我想使用JavaScript将数字转换为字母字符。例如,01 = n,02 = i 03 = n,04 = a等

当有人输入数字:01020304时,他会收到回复:nina。用户输入的内容将替换为包含空格的等效字符。

更新

谢谢大家的快速回复。我在一个站点中找到了这段代码。它将字母字符转换为数字,但是将数字转换为字母字符的代码不起作用。以下是将字母字符转换为数字的代码:

var i,j;
var getc;
var len;
var num, alpha;

num=new Array("01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17",
"18","19","20","21","22","23","24","25","26","00","##","$$");

alpha=new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","
v","w","x","y","z"," ",".",",");

function encode() {
  len=document.f1.ta1.value.length;
  document.f1.ta2.value="";
  for(i=0;i<len;i++) {
    getc=document.f1.ta1.value.charAt(i);
    getc=getc.toLowerCase();
    for(j=0;j<alpha.length;j++) {
      if(alpha[j]==getc) {
        document.f1.ta2.value+=num[j];
      }
    }
  }
}

任何人都可以告诉我如何转换它来进行相反的字符转换吗?

2 个答案:

答案 0 :(得分:2)

我同意Skrilldrick,你应该自己学习如何做到这一点,但我无法自拔:http://jsfiddle.net/dQkxw/

<强> HTML

<html>
    <body>
        <input type="text" id="code">
        <button onclick="decode($('#code').val())">
            Decode
        </button>
    </body>
</html>

<强>的JavaScript

window.decode = function(numbers) {
    if (numbers.length % 2 != 0)
    {
        alert("invalid code!");
        return;
    }

    var result = "";
    for (var i = 0; i < numbers.length; i+=2) {
        var number = Number(numbers.substring(i, i+2));
        if (number < 1 || number > 26)
        {
            alert("invalid number: "+number);
            return;
        }

        result += String.fromCharCode(96+number);
    }

    alert(result);
}

答案 1 :(得分:1)

一种很容易做到这一点的好方法,因此它是一个可扩展的解决方案,就是拥有一个多维数组,将每个char映射到它的相应char。每次转换都可以有多个维度,并在它们之间进行选择。

var myCharArray=new Array(4)
for (i=0; i < 4; i++)
myCharArray[i]=new Array(2)

myCharArray[0][0]="a"
myCharArray[0][1]="1"
myCharArray[1][0]="b"
myCharArray[1][1]="2"
myCharArray[2][0]="c"
myCharArray[2][1]="3"
myCharArray[3][0]="d"
myCharArray[3][1]="4"

然后,转换后,循环字符串中的每个字符进行编码,并在数组中搜索它。如果找到,请使用编码值进行切换。这应该相当容易。

您描述的方法似乎是Caesar cipher的简单衍生物。还要记住,因为脚本是客户端,所以解码起来会非常容易,所以请确保它不是重要的!