user254883
user254883

Reputation: 605

Replace array values with new defined values in Javascript

//Get message from textarea
var msg = $('#mytextarea').val();

//Convert string to array of letters
// eg. cata = ['c','a','t','a']
var msgLettersAsArray = msg.split('');

What I need to do now is replace the single letters,something like this

c = b;
a = e;
t = c;
a = e;

//array neeeds to be converted from this:
var array = ['c','a','t','a'];

// to this:
var array = ['b','e','c','e'];

Is there any way to achieve this? All I need to do is replace the letters that are already in the array with letters of my choice

Upvotes: 0

Views: 94

Answers (7)

plalx
plalx

Reputation: 43718

It's quite simple, just define a translation map and use Array.prototype.map.

var translationMap = {
    c: 'b',
    a: 'e',
    t: 'c'
};

//returns ['b','e','c','e']
['c','a','t','a'].map(function (letter) { return translationMap[letter] || letter; });

EDIT: It seems you actually just wanted to replace letters in the string, in this case @phylax answer would be correct. There is no need to use arrays for a simple string replacement.

Upvotes: 3

phylax
phylax

Reputation: 2086

Just making an answer out of my comment:

Like OP said, its ok to be done without the split(). And its possible to do with only one call to String.replace():

var map = {
  c: 'b',
  a: 'e',
  t: 'c'
};

msg.replace(/[a-z0-9]/g, function (i) { return map[i] || i; })

The RegExp can possibly made event simpler:

msg.replace(/./g, function (i) { return map[i] || i; })

Upvotes: 0

Chirag Bhatia - chirag64
Chirag Bhatia - chirag64

Reputation: 4516

I would recommend using a switch-case for every element in the array.

for (i in array) {
    switch (array[i]) {
    case "c":
        array[i] = "b";
        break;
    case "a":
        array[i] = "e";
        break;
    case "t":
        array[i] = "c";
        break;
    }
}

Upvotes: 0

vijay
vijay

Reputation: 10997

RUN THIS IN YOUR FIRE BUG CONSOLE

var array = ['c','a','t','a'];
var myarray = [];
for(i=0; i<=array.length; i++)
{
    if(array[i] == 'c' )
    {
        array[i] = 'b'
    }
    if(array[i] == 'a' )
    {
        array[i] = 'e'
    }
    if(array[i] == 't' )
    { 
        array[i] = 'c'
    }
    if(array[i] == 'a' )
    {
        array[i] = 'a'
    }
}

console.log(myarray);

Upvotes: 0

Filippo oretti
Filippo oretti

Reputation: 49817

not tested but it should work

 var replaxe = {
     'c':'b',
     'e':'d'
    },
  array = ['c','e'],
  result = [];

  for(var item in array){
    result.push(replaxe[item]);
  }


  console.log(result);

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 148980

Sure, just use a for loop:

var array = ['c','a','t','a'];
for (var i = 0; i < array.length; i++)
{
    var cur = array[i];
    if (cur == 'c') {
        array[i] = 'b';
    } else if (cur == 'a') {
        array[i] = 't';
    } else if (cur == 't') {
        array[i] = 'c';
    }
}

But using an object to store these mappings can make your code even more compact:

var array = ['c','a','t','a'];
var transform = { 'c': 'b', 'a': 'e', 't': 'c' };
for (var i = 0; i < array.length; i++)
{
    array[i] = transform[array[i]];
}

Upvotes: 0

Bergi
Bergi

Reputation: 664256

function replaceChars(str, map) {
    var i, reg = "";
    for (i in map)
        reg += i;
    return str.replace(
        new RegExp("["+reg.replace(/(\]|-|\\)/,"\\$1")+"]",'g'),
        function(char) { return map[char]; }
    );
}
//Get message from textarea
var msg = $('#mytextarea').val(); // "cata"

replaceChars(msg, {c:'b', a:'e', t:'c', a:'e'}); // "bece"

Upvotes: 1

Related Questions