javascript字符串替换方法

时间:2013-07-26 17:00:19

标签: javascript html json dom

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

1 个答案:

答案 0 :(得分:0)

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

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