[英]how do I get rid of selected words from a string
我如何摆脱一个字符串中的选定单词,这是我尝试过的
<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);
如果要摆脱不需要的单词,可以使用string#replace
和regex
。 您不必每次执行replace()
时都需要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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.