如何摆脱字符串中的选定单词

如何摆脱字符串中的选定单词

如何摆脱字符串中的选定单词
香港专业教育学院尝试过的

<html>
<body>
<p align="center"><input type="text" id="myText"
 placeholder="Definition"></p>
<p align="center"><button class="button-three" onclick="BoiFunction()"><p
 align="center">boii         </p></button></p>
 <font color="black"><p align="center" id="demo"></p></font>
 </body>
</html>


function BoiFunction() {
var str = document.getElementById("myText").value;
var output = document.getElementById("demo");
var GarbageWords = str.split(",").split("by");
output.innerHTML = GarbageWords;
}

最佳答案

代替.split(),您可以仅将.replace()与正则表达式一起使用。



// ", " and " by " are to be removed from the string
var str = "A string, that by has, some by bad words in, by it.";
// Replace ", " globally in the string with just " "
// and replace " by " globally in the string with just " "
str = str.replace(/,\s/g," ").replace(/\sby\s/g," ");
console.log(str);





或者,对于更自动化的版本:



// Array to hold bad words
var badWords = [",", "by", "#"];

var str = "A string, that by has, #some# by bad words in, by it.";

// Loop through the array and remove each bad word
badWords.forEach(function(word){
  var reg = new RegExp(word, "g");
  var replace = (word === "," || word === "by") ? " " : "";
  str = str.replace(reg, replace);
});

console.log(str);

关于javascript - 如何摆脱字符串中的选定单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45393642/

10-09 02:06