2013-07-26 83 views
0

我有一个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? 
    } 
} 
+0

'quiz [0] .Question'是否是'“”'是否正确?你知道'.indexOf'函数吗? – Halcyon

+0

没有。它包含我需要替换的元素当然,因为我试图只输入s的内容而不是变量s – user1968057

+0

我玩了一下,看起来你的代码很好。 [小提琴](http://jsfiddle.net/4Zw3M/1023/) – zsong

回答

0

我没有看到任何问题与您的代码。 http://jsfiddle.net/VBgx4/3/

所以s是一个正在传递到你的函数的字符串。如果Question包含等于s的子字符串,则它将替换该匹配部分Question。如果s不在Question那么Question将保持不变。

+0

这就是我认为也是,因为我有另一个事件触发此事件? – user1968057

+0

我会编辑它的代码来显示更多信息 – user1968057