JavaScript_javascript 기술로 sprintf 및 printf 함수 구현

WBOY
풀어 주다: 2016-05-16 16:18:02
원래의
3175명이 탐색했습니다.

대부분의 언어에서 발견되는 sprintf / printf 함수를 JavaScript로 구현하세요.

http://www.webtoolkit.info/javascript-sprintf.html: sprintf 함수의 비교적 완전한 시뮬레이션입니다. 사용 가능한 형식 와일드카드:
1.%% - 백분율 기호 자체를 반환합니다
2.%b - 이진수
3.%c - ASCII 대응 문자
4.%d - 정수
5.%f - 부동 소수점 숫자
6.%o - 8진수
7.%s - 문자열
8.%x - 16진수(소문자 형식)
9.%X - 16진수(대문자 형식)

% 기호와 와일드카드 문자 사이에 사용 가능한 옵션은 다음과 같습니다(예: %.2f).

1. (숫자 앞에 & - 기호를 양수와 음수의 기호로 표시하도록 강제합니다. 기본적으로 음수에만 - 기호가 표시됩니다.)
2.- (변수 왼쪽 정렬)
3.0(오른쪽 정렬 패딩 문자로 0 사용)
4.[0-9] (변수의 최소 너비 설정)
5..[0-9] (부동 소수점 정밀도 또는 문자열 길이 설정)

코드 복사 코드는 다음과 같습니다.

/**
*
*  자바스크립트 스프린트f
http://www.webtoolkit.info/
*
*
**/

sprintfWrapper = {

  init : 함수 () {

    if (인수 유형 == "정의되지 않음") { return null; }
    if (arguments.length < 1) { 반환 null; }
    if (인수 유형[0] != "string") { return null; }
    if (regExp 유형 == "정의되지 않음") { return null; }

    var 문자열 = 인수[0];
    var exp = new RegExp(/(%([%]|(-)?( |x20)?(0)?(d )?(.(d)?)?([bcdfosxX])))/g);
    var match = new Array();
    var strings = new Array();
    var 전환수 = 0;
    var stringPosStart = 0;
    var stringPosEnd = 0;
    var matchPosEnd = 0;
    var newString = '';
    var 일치 = null;

    while (일치 = exp.exec(문자열)) {
      if (match[9]) { convCount = 1; }

      stringPosStart = matchPosEnd;
      stringPosEnd = exp.lastIndex - match[0].length;
      strings[strings.length] = string.substring(stringPosStart, stringPosEnd);

      matchPosEnd = exp.lastIndex;
      일치[matches.length] = {
        일치: 일치[0],
        왼쪽: match[3] ? 사실 : 거짓,
        기호: match[4] || '',
        패드: match[5] || '',
        최소: 일치[6] || 0,
        정밀도: match[8],
        코드: match[9] || '%',
        부정:parseInt(arguments[convCount]) < 0? 사실 : 거짓,
        인수: 문자열(인수[convCount])
      };
    }
    문자열[strings.length] = 문자열.substring(matchPosEnd);

    if (matches.length == 0) { 반환 문자열; }
    if ((arguments.length - 1) < convCount) { return null; }

    변수 코드 = null;
    var 일치 = null;
    var i = null;

    for (i=0; i

      if (matches[i].code == '%') { 치환 = '%' }
      else if (matches[i].code == 'b') {
        match[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
        대체 = sprintfWrapper.convert(matches[i], true);
      }
      else if (matches[i].code == 'c') {
        match[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
        대체 = sprintfWrapper.convert(matches[i], true);
      }
      else if (matches[i].code == 'd') {
        match[i].argument = String(Math.abs(parseInt(matches[i].argument)));
        대체 = sprintfWrapper.convert(matches[i]);
      }
      else if (matches[i].code == 'f') {
        match[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? match[i].precision : 6));
        대체 = sprintfWrapper.convert(matches[i]);
      }
      else if (matches[i].code == 'o') {
        match[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
        대체 = sprintfWrapper.convert(matches[i]);
      }
      else if (matches[i].code == 's') {
        match[i].argument = match[i].argument.substring(0, match[i].precision ? match[i].precision : match[i].argument.length)
        대체 = sprintfWrapper.convert(matches[i], true);
      }
      else if (matches[i].code == 'x') {
        match[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
        대체 = sprintfWrapper.convert(matches[i]);
      }
      else if (matches[i].code == 'X') {
        match[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
        대체 = sprintfWrapper.convert(matches[i]).toUpperCase();
      }
      그렇지 않으면 {
        대체 = 일치[i].match;
      }

      newString = 문자열[i];
      newString = 대체;

    }
    newString = 문자열[i];

    newString을 반환합니다.

  },

  변환 : 함수(일치, nosign){
    if (nosign) {
      match.sign = '';
    } 그 밖의 {
      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;
      } 그 밖의 {
        반환 패드 match.sign match.argument;
      }
    } 그 밖의 {
      if (match.pad == "0" || nosign) {
        return match.sign match.argument pad.replace(/0/g, ' ');
      } 그 밖의 {
        return match.sign match.argument pad;
      }
    }
  }
}

sprintf = sprintfWrapper.init;

추가 형식 지정 없이 단순히 위치 변수의 내용을 바꾸려면 비교적 간단한 YUI 도구에서 제공되는 printf를 사용할 수 있습니다.

코드 복사 코드는 다음과 같습니다.

YAHOO.Tools.printf = function() {
var num = 인수.길이;
var oStr = 인수[0];
for (var i = 1; i var 패턴 = "\{" (i-1) "\}";
var re = new RegExp(패턴, "g");
oStr = oStr.replace(re, 인수[i]);
}
oStr 반환
}

YAHOO.Tools.printf("Display string {0}, {1}.", "1", "2")와 같이 사용하는 경우 {?}를 사용하여 일치시킵니다.

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!