如何在Javascript中替换内容

时间:2016-09-21 08:50:20

标签: javascript

function show(question,answer)
{        
  document.getElementById("question").innerHTML = question;       
  document.getElementById("answer").innerHTML = answer;               
}

我需要将单引号'替换为问题和答案中的\'

1 个答案:

答案 0 :(得分:0)



$(document).ready(function(){
  var question = "this is ' new ' question ' from my side";
  var answer = "this is ' new ' answer ' from my side";
  showContent(question, answer);
});

function showContent(question, answer) {
  document.getElementById("question").innerHTML = ReplaceString(question,"'","\\'");
  document.getElementById("answer").innerHTML = ReplaceString(answer, "'", "\\'");
}

function ReplaceString(message, oldString, newString) {        
  return message.split(oldString).join(newString);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question"></div>
<div id="answer"></div>
&#13;
&#13;
&#13;