一道Javascript面试题

字符串正则替换:

TIM图片20170327181950.png

写了一个比较挫的实现,利用replace正则的特点,a是匹配到的字符串,b是字符串的起始位置。因此偷懒匹配两次,第一匹配把位置关系和fn中arguments数组的索引对应上,第二次匹配直接替换。

(function (window) {
        function fn(str) {
            this.str = str;
        }
        fn.prototype.format = function () {
            var arg = arguments;
            return this.str.replace(/\?\?\{(\d)+\}/g, function (a, b) {
                return arg[b] || '';
            });
        };

        window.fn = fn;
    })(window);

    (function () {
        var t = new fn('

??{1}??{2}

'); console.log(t.format('http://www.yonghongtech.com', 'yonghong', 'welcome')); })();

你可能感兴趣的:(一道Javascript面试题)