Skip to content

Instantly share code, notes, and snippets.

Created December 27, 2016 06:51
What would you like to do?
printf function with javascript
<pre class="source">printf('apple:{0}, banana:{1}, mango:{2}', 'red', 'yellow', 'green');</pre>
<pre class="result"></pre>
<hr />
출처 : <a href="" target="_blank"></a>

printf function with javascript

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

A Pen by redgoose on CodePen.


* 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