Javascript: How to have value in string represented by %s and then replaced with a value
I know this a really stupid question.
I'v开发者_如何学Pythone 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.
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);
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"
'Modern' ES6 solution: use template literals. Note the backticks!
var email = 'somebody@example.com';
var error_message = `An account already exists with the email: ${email}`;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
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
You may take a look at this : http://www.devbox.info/javascript-sprintf.html
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"
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.
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.
精彩评论