Skip to content

Instantly share code, notes, and snippets.

@Elevista
Last active March 4, 2016 00:40
Show Gist options
  • Save Elevista/b08a6f9a418dc484c425 to your computer and use it in GitHub Desktop.
Save Elevista/b08a6f9a418dc484c425 to your computer and use it in GitHub Desktop.
스트링 파라미터 치환

##Example

stringFormat("{1},{0}","two","one")
//returns "one,two"
stringFormat("{1},{0}",["two","one"])
//returns "one,two"
/**
* 문자열을 파리미터를 받아 치환 시킨다.
* @example <caption>인자는 배열 또는 일련의 파라미터로 받을 수 있다.</caption>
* stringFormat("{1},{0}","two","one")
* //returns "one,two"
* stringFormat("{1},{0}",["two","one"])
* //returns "one,two"
* @param {string} source - source string
* @param {...string|Array.<string>} params - Params to replace. It can be a Array
* @returns {string} 변환된 스트링
*/
function stringFormat(source, ...params) {
var args = params[0] instanceof Array ? params[0] : params;
var regex = /{(\d+)}/g;
return source.replace(regex, function (m, $1) {
return args[$1 * 1];
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment