我的 JavaScript 字符串替换方法有问题,我尝试了很多,但仍然不知道出了什么问题。请给我一些建议。谢谢。
基本上,我有一个问题字符串和一个数组答案,我想用“ __ ”替换问题字符串中的答案。
我有以下 JavaScript 数组:
但是当我尝试替换字符串时,发生了一些有趣的事情:
var quiz = [{
"Question": " ",
"Answer_choic": [],
"Answer": [],
"Points": 0,
"totalPoints": 0
}];
quiz[0].Question = String(document.getElementById('QuestionName').value)
//first
var QuestionArray= new Array();
function selectAnswers() {
var QuestionValue = document.getElementById("QuestionName").value;
//alert(QuestionValue);
quiz[0].Question=String(document.getElementById('QuestionName').value)
quiz[0].Points=parseInt(document.getElementById('Points').value);
quiz[0].totalPoints+=parseInt(document.getElementById('Points').value);
QuestionArray= QuestionValue.split(' ');
for(var i=0; i<QuestionArray.length; i++) {
QuestionArray[i] ='<span class="answerWord" id="Answer'+i+'" onclick="toggleAnswer('+i+');setAnswer(QuestionArray['+i+']) "> '+QuestionArray[i] +'</span>';
}
//then trigger this function
function setAnswer(s) {
//s is typeof string, i double check it
quiz[0].Answer.push(s);
// example of quiz[0].Question: "abc bbb aaa dddd"
// example of s will be any substring of above like: "bbb"
if (QuestionType.value == 'FillInLine') {
// this doesnt work
quiz[0].Question = quiz[0].Question.replace(s, '______');
//but if i change s to, let say a string "ab", and the question contain the substring "ab", it works fine. im really sure variable "s" is typeof string. Can anybody tell me why?
}
}