javascript - 按给定格式格式化文本

标签 javascript regex

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

相关文章:

javascript - 获取 Sencha 类的所有静态属性

javascript - 将文本与塞尔维亚西里尔字母相互转换

python - 将时间段字符串转换为值/单位对

c++ - 字母数字字符的正则表达式,.@&,’()+/: and one hyphen only

java - 如何删除某个字符之前的所有内容并将字符分成组

javascript - 使用 Exiftool 和 NodeJS 从 JPG 读取标签

javascript - Angular 类不是 Angular 模块

javascript - jQuery Sweet Alert 意外的第二个参数错误

java - 为什么找到的 token (antlr)中出现空白?

regex - 带有 HTTP GET 参数的 django url 调度程序