jQuery String Template Format Function

来源:互联网 发布:linux 常用命令 chm 编辑:程序博客网 时间:2024/05/22 14:06

https://www.sitepoint.com/jquery-string-template-format-function/

Pretty useful jQuery function I’ve called “formatVarString”. Its takes a string as the first argument with n arguments after with which to perform variable substitution (returning variables as part of a string using parenthesis).

You can simply use {1}, {2}, {3} etc to reference variables in a string.

Usage

formatVarString('we love {1}.', 'jQuery4u');//output: "we love jQuery4u."formatVarString('{1} is a {2} aimed to help you learn {3}.', 'jQuery4u', 'blog', 'jQuery');//output: "jQuery4u is a blog aimed to help you learn jQuery."The jQuery Format Function

源码:

var JQUERY4U = {};JQUERY4U.UTIL = {formatVarString: function()    {        var args = [].slice.call(arguments);        if(this.toString() != '[object Object]')        {            args.unshift(this.toString());        }        var pattern = new RegExp('{([1-' + args.length + '])}','g');        return String(args[0]).replace(pattern, function(match, index) { return args[index]; });    }}

使用:

JQUERY4U.UTIL.formatVarString('{1} is a {2} aimed to help you learn {3}.', 'jQuery4u', 'blog', 'jQuery');//output: "jQuery4u is a blog aimed to help you learn jQuery."

Was this helpful?
More:
javascript return string variables {1}

原创粉丝点击