我有一个JavaScript字符串替换方法的问题,我试了很多,仍然没有线索什么是错的。请给我一些建议。谢谢。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?
}
}
'quiz [0] .Question'是否是'“”'是否正确?你知道'.indexOf'函数吗? – Halcyon
没有。它包含我需要替换的元素当然,因为我试图只输入s的内容而不是变量s – user1968057
我玩了一下,看起来你的代码很好。 [小提琴](http://jsfiddle.net/4Zw3M/1023/) – zsong