Javascript字符串格式化-替换保存在变量中的字符串

Javascript string formatting - replace in string saved in a variable

本文关键字:字符串 变量 存在 替换 格式化 Javascript 保存      更新时间:2023-09-26

任务是简单地从1到99写入数字,并替换所有数字,其中:num (mod 3) =0与每个num (mod 5) =0 -> mat, num ( mod 3=0 && mod 5=0 )与每个mat,所有其他保持不变。这很简单,但格式很糟糕,所以我想这样做:在每个数字之间插入一个空格,并将每个"特殊"单词(可被3、5或两者整除)放在单独的行上。我知道我必须用string.prototype.format,但具体怎么用呢?下面是我当前的代码:

<html>
<body>
<p>Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>

function myFunction() {
     var text = []; 
      var res = " ";   
     for (i=1; i<100; i++){
   if (i%3 == 0 && i%5 == 0){
        text[i]= "SachMat ";
                }
       else if (i%3 == 0){
        text[i]= 'sach ';
                }
        else if (i%5 == 0){
        text[i]= 'mat ';
                }
        else {
        text[i]= i;                
                }       
      var res = res.concat(text[i]);
       }

 document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

试试这个

function myFunction() {
    var text = []; 
    var res = " ";   
    for (i=1; i<100; i++){
        if (i%3 == 0 && i%5 == 0){
            text[i]= "<br/>SachMat<br/>";
        } else if (i%3 == 0) {
            text[i]= 'sach ';
        } else if (i%5 == 0){
            text[i]= 'mat ';
        } else {
            text[i]= i;                
        }       
        res = res.concat(' ' + text[i]);
    }
    document.getElementById("demo").innerHTML = res;
}