<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>
我正在尝试将输出设置为:
12-31.23
最佳答案
您可以使用String#replace
带有计数器变量的方法。
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")
)
或者使用单个 for 循环,不需要嵌套循环,这会使其变得更加复杂。
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")
);
关于javascript - 按给定格式格式化文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41518865/