pwittke
pwittke

Reputation: 17

Javascript replace all?

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!

Upvotes: 0

Views: 327

Answers (1)

noob
noob

Reputation: 9212

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;

}

Upvotes: 1

Related Questions