LIGHT
LIGHT

Reputation: 5712

formatting text in given format

<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>

I am trying to get output as:

12-31.23

Upvotes: 0

Views: 35

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115272

You can use String#replace method with a counter variable.

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")
)


Or use a single for loop and there is no need for nested loop that makes it more complex.

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")
);

Upvotes: 1

Related Questions