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
Release: 2016-05-16 15:32:28
Original
1294 people have browsed it

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>
Copy after login

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>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template