当我在该数组中仅放置一个字母单词(“ s”,“ z”等)时,它可以工作,但是在这种情况下,它不起作用,我也不知道为什么。我知道那是这种情况,因为当我仅使用“ document.querySelector(”。area1“)。textContent = result;”没有if语句,它将起作用...
答案 0 :(得分:0)
检查以下代码是否适合您。
<!DOCTYPE html>
<html lang="en">
<body>
<button id="replaceBtn">Replace</button>
</body>
<script type="text/javascript">
var lett = ["Mně", "mě", "Mě", "mně"],//whatever you want to replace
replaceLett = ["M__","m_","M_","m__"],//whatever you want to replace with
texts = "Mně mě Mě mně",//your string
replaceButton = document.getElementById("replaceBtn"),
reg = [];
lett.forEach(function(item){
reg.push(new RegExp(item,"g"));//forming a regular expression for global replacement
});
console.log(reg);
replaceButton.addEventListener('click', function(){
lett.forEach(function(item, index){
texts = texts.replace(reg[index], replaceLett[index]);
console.log(texts);
});
});
</script>
</html>