Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.