如何从字符串中删除选定的单词

时间:2017-07-29 20:16:18

标签: javascript html

如何从字符串中删除选定的单词 这是我尝试过的

<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;
}

2 个答案:

答案 0 :(得分:2)

您可以将.split()与正则表达式一起使用,而不是.replace()

&#13;
&#13;
// ", " 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);
&#13;
&#13;
&#13;

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

&#13;
&#13;
// 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);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您想删除不需要的字词,可以使用string#replaceregex。每次执行join()时都不必replace(),因为您将获得一个新字符串。

此外,一旦你split()一个字符串,你得到一个数组,所以你需要join()得到另一个字符串,然后再split()为第二个字。

请查看工作演示。

function BoiFunction() {
  var str = document.getElementById('myText').value; 
  var output = document.getElementById('demo');
  var garbageWords = str.split(',').join('').split('by').join('');
  output.innerHTML = garbageWords;
  var garbageWords2 = str.replace(/,/g,'').replace(/by/g,'');
  document.getElementById('demoWithReplace').innerHTML = garbageWords2;
}
<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">With Split: <p align="center" id="demo"></p></font>
 <font color="black">With Replace: <p align="center" id="demoWithReplace"></p></font>