[英]javascript string replace method
我的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?
}
}
我看不到您的代碼有任何問題。 http://jsfiddle.net/VBgx4/3/
所以s是一個字符串,該字符串將傳遞到您的函數中。 如果Question
包含等於s
的子字符串,則它將替換Question
匹配部分。 如果s
不在Question
那么Question
將保持不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.