mammy wood
mammy wood

Reputation: 143

How do I use %s as a variable?

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?

Upvotes: 3

Views: 626

Answers (4)

Raunak Thakkar
Raunak Thakkar

Reputation: 9

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

Upvotes: -1

Sumeet Kumar Yadav
Sumeet Kumar Yadav

Reputation: 12985

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."

Upvotes: 4

Patrick Hund
Patrick Hund

Reputation: 20246

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

Upvotes: 0

Ilijanovic
Ilijanovic

Reputation: 14904

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");

Upvotes: 0

Related Questions