본문 바로가기

WebDev

javascript string formatter

javascript string formatter

stackoverflow 참고했고, {,}리터럴을 지원하도록 내가 약간 수정했다.
python의 string formatter는 멋짐 그 자체다. 자바스크립트에는 이런 기능이 없나 대충 찾아봤더니 잘 보이지 않는다. 그래서 이 기능을 구현해놓은 사람은 없나.. 했더니 역시 있었다.

python에서 했던 그대로 기본적인 포멧팅이 가능하다.

var format = function() {
    // python-style string formatter from http://stackoverflow.com/a/13639670/2050087
    // Examples
    //  "hello {} and {}".format("you", "bob");
    //  "hello {0} and {1}".format("you", "bob");
    //  "hello {0} and {1} and {a}".format("you", "bob", {a:"mary"});
    //  "hello {0} and {1} and {a} and {2}".format("you", "bob", "jill", {a:"mary"});
    var args = arguments;
    this.unkeyed_index = 0;
    return this.replace(/\{{1,2}(\w*)\}{1,2}/g, function(match, key) {
        if (match.indexOf('{{') !== -1) { // {{dont-replace}}
            return match.replace('{{', '{').replace('}}', '}');
        }
        if (key === '') { // {}
            key = this.unkeyed_index;
            this.unkeyed_index++
        }
        if (key == +key) { // {0}
            return args[key] !== 'undefined'
                ? args[key]
                : match;
        } else { // {named}
            for (var i = 0; i < args.length; i++) {
                if (typeof args[i] === 'object' && typeof args[i][key] !== 'undefined') {
                    return args[i][key];
                }
            }
            return match;
        }
    }.bind(this));
};
String.prototype.format = format;

'WebDev' 카테고리의 다른 글

css same width, height  (0) 2016.03.10
javascript object copy  (0) 2016.03.08
s3 sigv4  (0) 2016.03.03
AWS  (0) 2016.03.02
letsencrypt  (0) 2016.02.29