0

I am working on a loop to replace language tags {lang_vname} with the actual term (name)

language.js:

var lang = {
//common
   vname                   : "name",
   name                    : "lastname",
   adress                  : "adress",
   language                : "language",

replace script

function translate(output)  {
var term = output;
$.each(lang,function(i,l){
    var find = "{lang_"+i+"}";
    term = term.replace(find,l);
});
return term;}

I can't figure out how to replace the output if there is more than one expression of one kind. It's only replacing the first one and if there is a second tag of it it displays the tag. I found a solution like replace(/find/g,l); but it is not working here and stops my whole script.
Is there a way to solve that easily ?

EDIT

thanks to Felix Kling! the link he provided made it work :D my final result is

function translate(output)  {
    var term = output;
    $.each(lang,function(i,l){
        var find = "{lang_"+i+"}";
        var regex = new RegExp(find, "g");
        term = term.replace(regex, l);  
    });
    return term;
}

thanks for your fast help!

pwittke
  • 17
  • 1
  • 9
  • what is the format and type of the output variable ? – amd Jan 16 '12 at 10:49
  • possible duplicate of [In Javascript, how can i perform a global replace on string with a variable inside '/' and '/g'?](http://stackoverflow.com/questions/542232/in-javascript-how-can-i-perform-a-global-replace-on-string-with-a-variable-insi) – Felix Kling Jan 16 '12 at 10:50

1 Answers1

1

If this won't work for you please provide an example for the variable output

function translate(output)  {
    var term = output;
    $.each(lang, function(i, l){
        var find = new RegExp("{lang_"+i+"}", "g");
        term = term.replace(find, l);
    });
    return term;

}
noob
  • 8,982
  • 4
  • 37
  • 65
  • something like this for example : var output = ""; its working for single expressions but as soon as there is sth twice its not replacing both – pwittke Jan 16 '12 at 11:27
  • yes i combined both but the link by Felix Kling helped me to understand the issue :) thanks for your help – pwittke Jan 16 '12 at 12:23