【发布时间】:2017-01-03 14:15:44
【问题描述】:
我有字符串 format,其中包含数字 {0}、{1}、{2}。我希望这些数字被输入类型placeholder = "Outside,beautiful,blue" 中的占位符写入的单词替换,即format[i+1] 的值等于字符串words 的索引(包含占位符中的单词)。结果在控制台中得到这样的东西:
外面是如此美丽,蓝天,美丽的大自然和蓝色太平洋旁边的房子......
HTML:
<!Doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Exercises in JS</title>
<script src="exercises.js"></script>
<body>
<label for="myText">Input array:</label>
<input type="text" name="wordcount" id="myText" placeholder = "Outside,beautiful,blue" value="" />
<a href="#" id="sub">Submit</a>
</body>
</head>
</html>
Javacript 代码:
window.onload = function(){
inputBox = document.getElementById("myText");
btn = document.getElementById('sub');
btn.addEventListener("click",function(event){
event.preventDefault();
stringFormat(inputBox.value);
});
str = inputBox.value;
var format = '{0} is so {1} with {2} sky, {1} nature and house next to the {2} pacific ocean...';
function stringFormat(str) {
var words = document.getElementById("myText").placeholder.split(",");
for (var i = 0; i < format.length; i++) {
if (format[i] === '{' && format[i+1] == '0') {
format = format.replace(format[i+1], words[i]);
}
else if (format[i] === '{' && format[i+1] > '0') {
format = format.replace(format[i+1], words['$[i]']);
}
}
console.log(format);
}
}
【问题讨论】:
-
不要遍历输入字符串,而是遍历 words 数组,每个循环只替换 "{" + i + "}"
标签: javascript string methods