views:

81

answers:

2

Using JavaScript's replace and regex, how do I replace numbers 0-9 with the letters a-j ?

example mapping: 0 = a, 1 = b, 2 = c, 3 = d, 4 = e and so on.

so, before:

x = 3;

after:

x = 'd';
+7  A: 

Most straightforward for me is to simply map one value to another:

var map = [
    'a','b','c',
    'd','e','f',
    'g','h','i'
];

var x = 3;
x = map[x];

Of course, you can generate the mapping using less typing:

var map = 'abcdefghi'.split('');

And if you need more complicated mapping you can always use an object:

var complicatedMap = {
   10 : 'a',
   55 : 'b' /* etc ... */
}
slebetman
Perfect, thanks!
k00k
A: 

Another way:

function code9(s){
    return s.replace(/\d/g, function(c){
        return String.fromCharCode(+c+97);
    })
}

var s='August 23, 2010';
alert(code9(s));

/*  returned value: (String)
August cd, caba
*/
kennebec