Javascript simulation to achieve c-sharp string.format function function code

  • 2020-03-30 00:00:37
  • OfStack

C# string.format this function used more places, so js implementation of a simple version:


String.format = function ()
        {
            var formatStr = arguments[0];
            if ( typeof formatStr === 'string' )
            {
                var pattern,
                    length = arguments.length;
                for ( var i = 1; i < length; i++ )
                {
                    pattern = new RegExp( '\{' + ( i - 1 ) + '\}', 'g' );
                    formatStr = formatStr.replace( pattern, arguments[i] );
                }
            } else
            {
                formatStr = '';
            }
            return formatStr;
        };

The above code adds a static method format to the javascript String class, and then its usage is exactly the same as c#'s string.format, the test is as follows:


String.format('http://wcf.open.a.com/blog/sitehome/paged/{0}/{1}',1,20)
 Output:  "http://wcf.open.a.com/blog/sitehome/paged/1/20"


String.format('{0}+{0}+{1}={2}',1,2,1+1+2)
 The output : "1+1+2=4"


String.format({name:'leonwang'},'hello,world')
 The output : ""

If the first parameter is not of type string, simply return an empty string without further processing.


Related articles: