Using arrays to change color of certain words in an input box

后端 未结 5 735
温柔的废话
温柔的废话 2021-01-21 18:40

So I\'m working on a JSFiddle and I\'m a little confused about something. I have an input box called myTextField with a random paragraph and a button that calls my change functi

5条回答
  •  -上瘾入骨i
    2021-01-21 19:20

    Here's my take on it using one regex and no looping. At its core, it relies on the regular expression /(^|\W)(every|most|...|your)(?=\W|$)/g for replacement.

    my_change = function(){
    
      var myNewTitle = document.getElementById('myTextField').value;
      if( myNewTitle.length==0 ){
        alert('Write Some real Text please.');
        return;
      }
    
      var title = document.getElementById('title');
    
      var matches = ["every", "most", "that", "half", "much", "the", "another", "her", "my", "their", "a", "an", "his", "neither", "these", "all", "its", "no", "this", "any", "those", "both", "least", "our", "what", "each", "less", "several", "which", "either", "many", "some", "whose", "enough", "more", "such", "your"];
    
      var r = new RegExp('(^|\\W)('+matches.join('|')+')(?=\\W|$)', 'g');
      title.innerHTML = myNewTitle.replace(r, '$1$2');
    
    };
    
    my_remove = function(){
      document.getElementById('title').innerHTML = "";
    }
    span { color: blue; }
    
    
    
    
    
    

提交回复
热议问题