2017-01-07 5 views
0
<script type="text/javascript"> 
function format1(txtnumber,txtformat){ 
    var fin = []; 
    for (var i = 0, len = txtnumber.length; i < len; i++) { 
     for (var j = 0, len = txtformat.length; j < len; j++) { 
      if(txtformat[i]=="x"){ 
       fin.push(txtnumber[i]); 
       break; 
      }else{ 
       fin.push(txtformat[j]); 
       break; 
      } 
     } 
    } 
    alert(fin); 
} 
format1("123123","xx-#x.#x"); 
</script> 

Ich versuche Ausgabe zu erhalten wie:Formatierung von Text in bestimmtem Format

12-31.23

Antwort

1

Sie String#replace Methode mit einem Zählervariable verwenden können.

function format1(txtnumber, txtformat) { 
 
    // initialize counter varibale 
 
    var i = 0; 
 
    // replace all # and x from format 
 
    return txtformat.replace(/[#x]/g, function() { 
 
    // retrive corresponding char from number string 
 
    // and increment counter 
 
    return txtnumber[i++]; 
 
    }) 
 
} 
 
console.log(
 
    format1("123123", "xx-#x.#x") 
 
)


oder eine einzelne for-Schleife verwenden und es besteht keine Notwendigkeit für verschachtelte Schleife, die es komplizierter macht.

function format1(txtnumber, txtformat) { 
 
    // initialize string as empty string 
 
    var fin = ''; 
 
    // iterate over format string 
 
    for (var i = 0, j = 0, len = txtformat.length; i < len; i++) { 
 
    // if char is x or # concatenate the number 
 
    // from string and increment the counter 
 
    // else return the existing character 
 
    fin += txtformat[i] == 'x' || txtformat[i] == '#' ? txtnumber[j++] : txtformat[i]; 
 
    } 
 
    return fin; 
 
} 
 
console.log(
 
    format1("123123", "xx-#x.#x") 
 
);