How do I use %s as a variable?

Viewed 175

I have a messages object like below

const messages = 
{
  msg1: "the length is less by %s"
  msg2: "the length is greater by %s"
}

I want to set it as a variable given a value

const value = 6
const check = messages.msg2 % value
console.log(check) // the length is greater by 6 

Above is how you would do it in python using %. In javascript it gives NaN. How do I do this in javascript?

4 Answers
let a = 5;
let b = 10;
console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`);

In your case of reusability

var message = function(a,b){

    return `Fifteen is ${a + b} and not ${2 * a + b}.`
}

message(10,5) // "Fifteen is 30 and not 40."

Something like this? For example in console.log() has an second argument

JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output.

const messages = 
{
  msg1: "the length is less by %s, and this is an %s",
  msg2: "the length is greater by %s"
}

console.log(messages.msg1, 5, "test");

JavaScript does not have C style string formatting built in like Python does. You can write a function that emulates it, like this:

const messages = {
  msg1: 'the length is less by %s',
  msg2: 'the length is greater by %s'
};

function formats(string, ...args) {
  const tokens = string.split(/%s/);
  let str = '';
  for (let i = 0; i < tokens.length; i++) {
    str = `${str}${tokens[i]}${i < args.length ? args[i] : ''}`;
  }
  return str;
}

const value = 6;
const check = formats(messages.msg2, value);
console.log(check); // the length is greater by 6

messages=(value)=>{ return(the length ${value}) } console.log(messages(6)) //the length 6

Related