Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In javascript i have an array with words i would like to censor after putting some text in textarea, and when the word in it matches one in array, it is being replaced with "****". The problem is: for example the banned word is "word1", and when i trigger the event with clicking on "censor" button, the textarea.value, which is (for example) "word1!" is being replaced on "*****", but i want it to be "*****!".

There are no loops, cause i just tried to apply the algorithm for single banned word. Couldn't even do that. The 'start' variable is for further searching of other banned words within the textarea.value. Everything should be done with basic string/array methods, without using Regular Expressions.

let getId = x => document.getElementById(x);
let banned = ['word1','word2','word3'];
let start = 0;

getId('censor').addEventListener('click', function(){
let stars = '';
for(let i=0;i < banned[0].length; i++) {
    stars+= '*';
}
let str = getId('text').value;
str = str.split(' ');
let found = str.indexOf(banned[0],start);
str.splice(found,1, stars);
str = str.join(' ');
getId('text').value = str;
})
<div class="container">
    <form action="">
        <input type="text" id="banInput">
        <input type="button" value="Add word" id="add">
    </form>
    <textarea name="" id="text"></textarea>
    <input type="button" value="censor" id="censor">
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
212 views
Welcome To Ask or Share your Answers For Others

1 Answer

let getId = x => document.getElementById(x);
let banned = ['word1', 'word2', 'word3'];

getId('add').addEventListener('click', function() {
  banned.push(getId('banInput').value)
  getId('banInput').value = ''
  console.log(banned)
})

getId('censor').addEventListener('click', function() {

  let str = getId('text').value;
  let arr = str.split(//) // array of words
  let censored = arr.map(word => banned.includes(word) ? //if word is in banned
    '*'.repeat(word.length) // replace with *
    :
    word) // leave as is

  getId('text').value = censored.join(''); // back to string
})
<div class="container">
  <form action="">
    <input type="text" id="banInput">
    <input type="button" value="Add word" id="add">
  </form>
  <textarea name="" id="text"></textarea>
  <input type="button" value="censor" id="censor">
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...