16

I know this a really stupid question.

I've had a good few years experience with javascript but this one thing seems to have skipped my mind, my head has gone blank and I can't remember what it's called and how I would go about doing it.

Basically what I'm looking for is when you have a string variable such as:

var error_message = "An account already exists with the email: %s"

And you then pass a string somehow into this and it replaces the %s.

I probably sound really idiotic, but I'd really appreciate the help / reminding!

Thanks guys.

8 Answers 8

12

You just use the replace method:

error_message = error_message.replace('%s', email);

This will only replace the first occurance, if you want to replace multiple occurances, you use a regular expression so that you can specify the global (g) flag:

error_message = error_message.replace(/%s/g, email);
11

Please find an example below, thanks.

/**
 * @param  {String} template
 * @param  {String[]} values
 * @return {String}
 */
function sprintf(template, values) {
  return template.replace(/%s/g, function() {
    return values.shift();
  });
}

Example usage:

sprintf('The quick %s %s jumps over the lazy %s', [
  'brown',
  'fox',
  'dog'
]);

Would output:

"The quick brown fox jumps over the lazy dog"
0
10

'Modern' ES6 solution: use template literals. Note the backticks!

var email = '[email protected]';
var error_message = `An account already exists with the email: ${email}`;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

1
  • 1
    Note: this only works if email is within scope. If you plan to save off formatted messages in another context (such as i18n or resource file) this won't work. Commented Dec 2, 2016 at 13:12
2

I just wrote a new function to handle this:

function sprint(str, o) {
    if (typeof str !== "string" || typeof o !== "object") {
        return;
    }
    var regex = /%s\(([a-zA-Z0-9_]{1,15})\)/g,
        i;
    if (regex.test(str)) {
        str = str.replace(regex, function (found, match) {
            return o[match];
        });
    } else {
        for (i in o) {
            str = str.replace(/%s/, o[i]);
        }
    }
    return str;
}

And a few tests:

// Ordered Array mode
var s0 = sprint("This is %s %s call, using an %s in order", ["a", "function", "array"]);

// Ordered|Unordered Obejct Literal mode
var s1 = sprint("This is a %s(sw) function, %s(ma)! You need to %s(ch) this out...", {
    ma: "mang",
    sw: "sweet", //This is purposely out of order
    ch: "check"
});

console.log(s0);
console.log(s1);

https://gist.github.com/mbjordan/5807011

1
  • Thanks it works. Very useful when you have an array of strings to map for each %s %s %s...
    – JLavoie
    Commented Jul 14, 2017 at 2:28
2

You may take a look at this : http://www.devbox.info/javascript-sprintf.html

4
  • Thanks, I will definitely bookmark this for future reference. That's where I got confused, between PHP and Javascript, thinking that there was a built in function. For the current project simply using the replace function will suffice.
    – jbx
    Commented Jul 23, 2010 at 15:36
  • recommending to close since the link is broken, removing any value from this answer Commented Apr 16, 2015 at 19:12
  • Link appears to be up at this time. It appears to be a reasonable sprintf implementation. Not sure it is possible to include the 'essential parts' without including the whole thing.
    – AShelly
    Commented Apr 16, 2015 at 20:51
  • "Content blocked by your organisation" - This Websense category is filtered: Adult Material. Thanks a lot, corporate IT!
    – cda01
    Commented Jul 27, 2015 at 2:53
2

You can write your own sprintf function:

function sprintf(str, ...args) {
  return args.reduce((_str, val) => _str.replace(/%s|%v|%d|%f|%d/, val), str);
}
const s  = sprintf("An account already exists with the email: %s", "SOME_ERROR");
console.log(s); // "An account already exists with the email: SOME_ERROR"

// OR bind this function in String's prototype

String.prototype.sprintf = function (...args) {
  return args.reduce((_str, val) => _str.replace(/%s|%v|%d|%f/, val), this);
};

const str = "one %s, two %d, three %v".sprintf(1, 2, 3);
console.log(str) // "one: 1, two: 2, three: 3"

you can pass multiple %s or %v or %d

const str2 = sprintf("one %s, two %d, three %v", 1, 2, 3)
console.log(str2); // "one: 1, two: 2, three: 3"
1

There is nothing quite like C's printf() or PHP's sprintf() functionality built into JavaScript. There is the replace() method of the string object which can be used to replace one thing with another - which could be used in this particular case, but it's limited.

There are several implementations around that others have written which cover a subset of sprintf()'s behaviour.

0

See below

var error_message = "An account already exists with the email: %s"

var myNewString = error_message.replace(" %s", newdata);

Example

<script type="text/javascript">
var visitorName = "Chuck";
var myOldString = "Hello username! I hope you enjoy your stay username.";
var myNewString = myOldString.replace("username", visitorName);

document.write("Old string =  " + myOldString); 
document.write("<br />New string = " + myNewString);

</script>

Output for above.

Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay username.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.