Javascript字符串格式化-替换保存在变量中的字符串
Javascript string formatting - replace in string saved in a variable
任务是简单地从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;
}
相关文章:
- 从带参数的字符串变量调用函数中的函数
- jquery字符串变量上的每个函数
- 我想将查询字符串变量添加到JSON名称/值对中
- 如何从字符串变量访问对象属性
- 以数组形式访问字符串变量的Javascript
- javascript时间戳插入字符串变量
- 在innerHTML中的getElementById中获取一个带引号的字符串变量
- 如何在Jquery html elemet属性中附加字符串变量
- 如何通过jsp表达式标记将java字符串变量传递给javascript函数
- 传递带有符号“”的字符串变量'"到函数
- 在 javascript 中字符串变量的 “'” 之前添加 ' '
- AngularJS字符串变量到使用sanitize的HTML元素
- 如何使用 JavaScript 比较字符串变量
- 使用 JSON.parse 将字符串(变量)转换为对象,错误意外标记
- 如何将字符串变量从PHP传递到Javascript
- 从包含另一个函数的字符串变量中返回一个函数
- 如何使用参数调用java脚本函数,其中参数来自字符串变量
- 如果通过字符串变量发送,HTML内部的子窗口将显示为文本
- 如何在ReactNative项目中将本地文本文件加载到字符串变量中
- 如何在javascript中用字符串变量替换一段文本