Home >Web Front-end >JS Tutorial >Implementation of sprintf function example of PHP based on JS_javascript skills

Implementation of sprintf function example of PHP based on JS_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:32:281280browse

The example in this article describes the implementation of PHP's sprintf function based on JS. Share it with everyone 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 parameter is the string containing "%s", and the other parameters are the corresponding variables used to replace "%s".

For example:

<script type="text/javascript">
var str = "床前%s明光,疑是%s上霜;举头%s明月,低头%s故乡。",
  var1 = "明",
  var2 = "地",
  var3 = "望",
  var4 = "思";
str = sprintf(str, var1, var2, var3, var4);
</script>

I hope this article will be helpful to everyone in JavaScript programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn