Undefined Web
Undefined Web

Reputation: 53

jQuery - Translate String From An Array

I have an array like this:

var en_af = {
    "Hello": "Hallo",
    "World": "Wereld"
};

And a string like this:

var str = "Hello World";

And my expected output:

Hallo Wereld

So I want to replace the keys with the values.

Upvotes: 1

Views: 193

Answers (5)

Ravi Dhoriya ツ
Ravi Dhoriya ツ

Reputation: 4414

Try this solution,

var en_af = {
    "Hello": "Hallo",
    "World": "Wereld"
};

var str = "Hello World";  //provide here keys to lookup in en_af array

var keys_from_str=str.split(" "); //making an array of keys from given string.

var output_string="";
for(i=0;i<keys_from_str.length;i++){  
   output_string+=en_af[keys_from_str[i]]+" ";  //get value for respected key from en_af and concatenate with output_string
}
output_string=output_string.trim(); //removing last extra space
console.log(output_string);

Demo jsFiddle

Upvotes: 1

AKD
AKD

Reputation: 3966

        var str = "Hello World";
        $(str.split(' ')).each(function (i, v) {
            $('body').append(' ' + en_af[v]);
        });

demo: http://jsfiddle.net/B8x4C/

Upvotes: 0

Nidhin S G
Nidhin S G

Reputation: 1695

str = str.split(" ");
output = en_af.str[0] +" "+ en_af.str[1];

you can get the output like Hallo Wereld if strg is "Hello World"

Upvotes: 0

maxime1992
maxime1992

Reputation: 23803

var str_output = "";

Start by spliting the keys array

var keys_array = str.split(' ');

And iterate on it

keys_array.each(function(index, value) {
   str_output = str_output + " " + en_af.value;
});

Delete first and last spaces

$.trim(str);

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

try, splitting and getting index value of original array:

var str = "Hello World";
var res = str.split(" ");

var output="";
for(var i =0; i < res.length-1;i++){
 output += en_af[res[i]];
}

Upvotes: 0

Related Questions