Skip to content

Instantly share code, notes, and snippets.

@redgoose-dev
Created December 27, 2016 06:51
Show Gist options
  • Save redgoose-dev/c3ac21d0cc0fc630f5632a0fe801967f to your computer and use it in GitHub Desktop.
Save redgoose-dev/c3ac21d0cc0fc630f5632a0fe801967f to your computer and use it in GitHub Desktop.
printf function with javascript
<section>
<h1>Command</h1>
<pre class="source">printf('apple:{0}, banana:{1}, mango:{2}', 'red', 'yellow', 'green');</pre>
</section>
<section>
<h1>Result</h1>
<pre class="result"></pre>
</section>
<hr />
<p>
출처 : <a href="http://stackoverflow.com/q/4974238" target="_blank">http://stackoverflow.com/q/4974238</a>
</p>

printf function with javascript

파이썬이나 C에서 사용되는 printf 함수같은것을 사용할일이 생겨서 만들게 된 함수

A Pen by redgoose on CodePen.

License.

/**
* printf
*
* @param {string} str
* @param {string} values
*/
function printf(str, ...values)
{
for (let i = 0; i < values.length; i++)
{
let pattern = `\\{${i}\\}`;
let replace = new RegExp(pattern, 'g');
str = str.replace(replace, values[i]);
}
return str;
}
// action
var result = printf('apple:{0}, banana:{1}, mango:{2}', 'red', 'yellow', 'green');
document.querySelector('.result').innerHTML = result;
.source, .result {
border: 1px solid #ccc;
padding: 15px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment