Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - JS Censoring algorithm

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...