简体   繁体   中英

how do I get rid of selected words from a string

how do I get rid of selected words from a string this is what ive tried

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

Instead of .split() , you can just use .replace() with a regular expression.

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

Or, for a more automated version:

 // 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); 

If you want to get rid of unwanted words you can use string#replace and regex . You don't have to join() every time you do replace() as you will get a new string.

Also, once you split() a string you get an array, so you need to join() to get another string and then split() again for the second word.

Please check the working demo.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM