javascript定义restful那种占位符url

文章摘抄

https://segmentfault.com/q/1010000009600515

工作中需要使用restful接口风格,为了方便大家开发,需要封装一个ajax请求,那么使用者最方便的方式就是像angular那样格式化url,即:

$resource('http://localhost:8080/web/user/:id/oper/:active',{id: '111',active: 'y'})

因此,我在网上找了相关方法,实现上述API方法

String.prototype.restfulFormat = function (param) {
	var that = this;
    if (param === undefined || param === null || param === {}) {
        return this;
    }

    let keys = Object.keys(param);
    for (let key of keys) {
        that = that.replace(new RegExp("\\{" + key + "\\}", "g"), param[key]);
    }
    return that;
};
var url = "http://localhost:8080/yunpan/{username}/aaa/{name}";
console.log( url.restfulFormat( {username: '111', name: 'yc'}));
/**
 * 扩展了 String 类型,给其添加格式化的功能,替换字符串中 {placeholder} 或者 {0}, {1} 等模式部分为参数中传入的字符串
 * 使用方法:
 *     'I can speak {language} since I was {age}'.restfulFormat({language: 'Javascript', age: 10})
 *     'I can speak {0} since I was {1}'.restfulFormat('Javascript', 10)
 * 输出都为:
 *     I can speak Javascript since I was 10
 *
 * @param replacements 用来替换 placeholder 的 JSON 对象或者数组
 */
String.prototype.restfulFormat = function(replacements) {
	var formatString = function (str, replacements) {
		replacements = (typeof replacements === 'object') ? replacements : Array.prototype.slice.call(arguments, 1);
		return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function(m, n) {
			if (m == '{{') { return '{'; }
			if (m == '}}') { return '}'; }
			return replacements[n];
		});
	};
    replacements = (typeof replacements === 'object') ? replacements : Array.prototype.slice.call(arguments, 0);
    return formatString(this, replacements);
}

相关推荐