sprintf function instance based on JS to implement PHP
- 2020-10-23 20:52:24
- OfStack
This article illustrates the sprintf function based on JS to implement PHP. To share for your reference, the details are as follows:
The function is as follows:
<script type="text/javascript">
function sprintf()
{
var arg = arguments,
str = arg[0] || '',
i, n;
for (i = 1, n = arg.length; i < n; i++) {
str = str.replace(/%s/, arg[i]);
}
return str;
}
</script>
The first argument is the string containing "%s", and the other arguments are the corresponding variables used to replace "%s".
Such as:
<script type="text/javascript">
var str = " The bed %s Ming Guang, I doubt it %s The frost on; Look up %s Moon, bow your head %s In my hometown. ",
var1 = " Ming ",
var2 = " to ",
var3 = " hope ",
var4 = " think ";
str = sprintf(str, var1, var2, var3 . var4);
</script>
I hope this article has been helpful in JavaScript programming.