_javascript techniques for implementing sprintf and printf functions in JavaScript

Source: Internet
Author: User
Tags abs sprintf

sprintf/printf functions in most languages are implemented in JavaScript.

Http://www.webtoolkit.info/javascript-sprintf.html: The complete simulation sprintf function function. Available formatting wildcard characters:
1.%%-Returns the percent sign itself
2.%B-Binary digits
3.%c-ascii the corresponding character
4.%d-Integer
5.%f-floating-point numbers
6.%o-Eight binary digits
7.%s-strings
8.%x-16 digits (lowercase letters)
9.%X-16 numbers (in uppercase)

The options available between the% and the wildcard characters include (for example,%.2f):

1.+ (Forces the + and-symbol to be shown as positive negative numbers before the number.) Only negative numbers appear by default-symbols)
2.-(left-aligned variable)
3.0 (use 0 as right-aligned padding character)
4.[0-9] (Sets the minimum width of the variable)
5..[0-9] (set floating-point precision or length of string)

Copy Code code as follows:

/**
*
* Javascript sprintf
* http://www.webtoolkit.info/
*
*
**/

Sprintfwrapper = {

Init:function () {

if (typeof arguments = = "undefined") {return null;}
if (Arguments.length < 1) {return null;}
if (typeof Arguments[0]!= "string") {return null;}
if (typeof RegExp = = "undefined") {return null;}

var string = Arguments[0];
var exp = new RegExp (/(%) ([%]| ( \-)? (\+|\x20)? (0)? (\d+)? (\. (\d)? ([bcdfosxx])) /g);
var matches = new Array ();
var strings = new Array ();
var convcount = 0;
var stringposstart = 0;
var stringposend = 0;
var matchposend = 0;
var newstring = ';
var match = null;

while (match = Exp.exec (string)) {
if (Match[9]) {convcount = 1;}

Stringposstart = Matchposend;
Stringposend = Exp.lastindex-match[0].length;
Strings[strings.length] = string.substring (Stringposstart, stringposend);

      matchposend = Exp.lastindex;
      Matches[matches.length] = {
        match : Match[0],
        left:match[3]? true:false,
    & nbsp;   Sign:match[4] | | ',
        pad:match[5] | | ',
        min:match[6] | | 0,
         Precision:match[8],
        code:match[9] | | '% ',
        negative:parseint (Arguments[convcount]) < 0 true:false,
        argument:string (Arguments[convcount])
      };
   }
    Strings[strings.length] = string.substring (matchposend);

if (Matches.length = = 0) {return string;}
if ((arguments.length-1) < Convcount) {return null;}

var code = NULL;
var match = null;
var i = null;

For (i=0 i<matches.length; i++) {

if (matches[i].code = = '% ') {substitution = '% '}
else if (Matches[i].code = = ' B ') {
Matches[i].argument = String (Math.Abs (parseint (matches[i].argument)). ToString (2));
substitution = Sprintfwrapper.convert (matches[i], true);
}
else if (Matches[i].code = = ' C ') {
Matches[i].argument = String (String.fromCharCode (parseint (Math.Abs (parseint))));
substitution = Sprintfwrapper.convert (matches[i], true);
}
else if (Matches[i].code = = ' d ') {
Matches[i].argument = String (Math.Abs (parseint (matches[i].argument)));
substitution = Sprintfwrapper.convert (matches[i]);
}
else if (Matches[i].code = = ' F ') {
Matches[i].argument = String (Math.Abs (parsefloat (matches[i].argument)). toFixed (matches[i].precision? matches[i). Precision:6));
substitution = Sprintfwrapper.convert (matches[i]);
}
else if (Matches[i].code = = ' O ') {
Matches[i].argument = String (Math.Abs (parseint (matches[i].argument)). ToString (8));
substitution = Sprintfwrapper.convert (matches[i]);
}
else if (Matches[i].code = = ' s ') {
matches[i].argument = matches[i].argument.substring (0, matches[i].precision? matches[i].precision:matches[i). Argument.length)
substitution = Sprintfwrapper.convert (matches[i], true);
}
else if (Matches[i].code = = ' x ') {
Matches[i].argument = String (Math.Abs (parseint (matches[i].argument)). ToString (16));
substitution = Sprintfwrapper.convert (matches[i]);
}
else if (Matches[i].code = = ' X ') {
Matches[i].argument = String (Math.Abs (parseint (matches[i].argument)). ToString (16));
substitution = Sprintfwrapper.convert (Matches[i]). toUpperCase ();
}
else {
substitution = Matches[i].match;
}

NewString + = Strings[i];
NewString + = substitution;

}
NewString + = Strings[i];

return newstring;

},

Convert:function (Match, nosign) {
if (nosign) {
Match.sign = ';
} else {
Match.sign = match.negative? '-': match.sign;
}
var L = match.min-match.argument.length + 1-match.sign.length;
var pad = new Array (L < 0 0:l). Join (Match.pad);
if (!match.left) {
if (Match.pad = = "0" | | nosign) {
return match.sign + pad + match.argument;
} else {
return pad + match.sign + match.argument;
}
} else {
if (Match.pad = = "0" | | nosign) {
Return match.sign + match.argument + pad.replace (/0/g, ' ");
} else {
Return match.sign + match.argument + pad;
}
}
}
}

sprintf = Sprintfwrapper.init;

If you just want to do a simple location variable content replacement without the need for additional formatting, you can use the simple YUI tools to provide the printf:

Copy Code code as follows:

YAHOO. tools.printf = function () {
var num = arguments.length;
var ostr = arguments[0];
for (var i = 1; i < num; i++) {
var pattern = "\\{" + (i-1) + "\}";
var re = new RegExp (Pattern, "G");
OSTR = Ostr.replace (Re, arguments[i]);
}
return ostr;
}

When used like YAHOO. Tools.printf ("display string {0}, {1}.") "," 1 "," 2 "); In this way, use the {?} To make a match.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.