Home > database >  node js custom localized string
node js custom localized string

Time:07-24

I am just learning node js. I want to localize a string. This is where I'm at right now.

var globals = {
  enUS: {
      color:'color is {0}',
      cell:'cell phone'
  },
  enGB: {
      color: 'colour is {0}',
      cell: 'mobile phone'
  }
};

what i want to do is assign blue to globals["enUS"].color. so I want to output "color is blue" in the console. or when I assign red, I want to output "color is red". how do I fix this code?

CodePudding user response:

You can use templates to insert variables inside strings.

var color = "red"; // or whatever you want

var globals = {
  enUS: {
    color: `color is ${color}`,
    cell: "cell phone"
  },
  enGB: {
    color: `colour is ${color}`,
    cell: "mobile phone"
  }
};

console.log(globals["enUS"].color);
console.log(globals["enGB"].color);

CodePudding user response:

You can do something like this:

var globals = {
  colorG: 'blue', //default
  enUS: {
    color: (color = globals.colorG) => `color is ${color}`,
    cell: "cell phone"
  },
  enGB: {
    color: (color = globals.colorG) => `color is ${color}`,
    cell: "mobile phone"
  }
};

console.log(globals["enUS"].color());
console.log(globals["enGB"].color('purple'));

You can change the default color or pass any color of your choice.

CodePudding user response:

var VAR_COLOR='red';
var globals = {
  enUS: {
      color:`color is ${VAR_COLOR}`,
      cell:'cell phone'
  },
  enGB: {
      color: `colour is ${VAR_COLOR}`,
      cell: 'mobile phone'
  }
};

You can try using the VAR_COLOR like this

  • Related