0

I'm wondering if a function exists that does this thing:

var greetings = "Hello %s, I'm %s"
greeting.replace('Mickey','Minnie');

// Should return: Hello Mickey, I'm Minnie

EDIT

Thank you all for the help!

I created a little node package for it, in case anyone needed something like this:

str-render link

4 Answers 4

6

You can use template literals in an IIFE:

const greetings = ((a, b) => `Hello ${a}, I'm ${b}`)('Mickey','Minnie');

console.log(greetings);

Sign up to request clarification or add additional context in comments.

Comments

1

If you're not able to use ES6 (template literals) or a polyfill, you can also pass a function to .replace().

See:

var greeting = "Hello %s, I'm %s"
var replacements = ['Mickey', 'Minnie'];

greeting.replace(/%s/g, function() {
  return replacements.shift();
});

This returns "Hello Mickey, I'm Minnie"

Comments

1

Using just "traditional" Javascript:

var greetings = "Hello %s, I'm %s"
(['Mickey','Minnie']).forEach (function (n) { greetings = greetings.replace ('%s', n) });

Comments

0

Thanks for you all!

I created a little node package for it, in case anyone needed something like this:

str-render link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.