开发者

Javascript/jQuery library to replace variables in text

开发者 https://www.devze.com 2023-04-01 15:21 出处:网络
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:

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

精彩评论

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