开发者

Javascript/jQuery library to replace variables in text

I have Javascript APIs where users call them with URLs. I may need to replace some parts of the URL, for example they might call my ajax photo upload API with their upload URL:

http://www.example.com/photos/upload/${username};jsessionid=l2k34523

I then need to post to that URL when my code uploads a photo, replacing the ${username}开发者_如何学运维. I can tell them how to format that username variable in the URL, but I have to allow them to insert variables like this.

Is there a good Javascript or jQuery library to easily replace variables like the above?


A simple format function can do the trick for you...

// add String prototype format function if it doesn't exist yet
if (jQuery.isFunction(String.prototype.format) === false)
{
    String.prototype.format = function () {
        var s = this;
        var i = arguments.length;
        while (i--)
        {
            s = s.replace(new RegExp('\\{' + i + '\\}', 'gim'), arguments[i]);
        }
        return s;
    };
}

So you can easily just use it as:

".../photos/upload/{0};jsessionid=l2k34523".format("JohnDoe");

or with multiple variables:

".../photos/upload/{0};jsessionid={1}".format("JohnDoe", "l2k34523");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜