파이썬이나 C에서 사용되는 printf 함수같은것을 사용할일이 생겨서 만들게 된 함수
Created
December 27, 2016 06:51
-
-
Save redgoose-dev/c3ac21d0cc0fc630f5632a0fe801967f to your computer and use it in GitHub Desktop.
printf function with javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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