2017-07-29 43 views
1

我如何才能從一個字符串 擺脫選定字去掉選擇的話這就是我用盡的.split()我如何才能從一個字符串

<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

相反,你可以只使用.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);

+0

我想只是純粹的javascript –

+0

@JoseSalgado這兩種解決方案都是純JavaScript。 –

0

如果你想擺脫你可以使用string#replaceregex不受歡迎的詞彙。您每次做replace()時都不必join(),因爲您會得到一個新的字符串。

而且,一旦你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>

相關問題