2017-07-29 6 views
1

から選択された単語を取り除くんどのようにこれは、あなただけの通常ので.replace()を使用することができ、IVEは.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

代わりにしようとしたものです表現。

// ", " 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()に新しい文字列を取得する必要はありません。また

、あなたが2番目の単語のために再度別の文字列と、その後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>

関連する問題