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

标签 javascript string.format

任务很简单,写入从 1 到 99 的数字,并将其中的所有数字替换为:num (mod 3) =0 与每个 num (mod 5) =0 -> mat, num ( mod 3=0 && mod 5=0 ) 每个垫子,所有其他保持不变。这很简单,但格式很糟糕,所以我想这样做:在每个数字之间插入一个空格,并将每个“特殊”单词(可被 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;
}

关于Javascript 字符串格式 - 替换保存在变量中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32648629/

相关文章:

c# - C# 中需要 String.Format 以抛出参数不匹配的编译时错误

c# - 字符串.格式。查看需要的格式是否存在

javascript - 我想在 menuData.json 中显示 Products.MenuName

javascript - $.ajax 相当于 $.load 内容过滤器

c# - 绑定(bind)到 Entry.Text 的属性 setter 无限循环

c# - String.Format 结合 CultureInfo C#

javascript - 使用 JavaScript 打印 HTML Object 标签的内容

javascript - 将参数传递给类构造函数

javascript - 在 Javascript 中添加转换速度