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

后端 未结 5 736
温柔的废话
温柔的废话 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条回答
  • 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<span>$2</span>');
    
    };
    
    my_remove = function(){
      document.getElementById('title').innerHTML = "";
    }
    span { color: blue; }
    <input type="text" id="myTextField" value ="It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife. However little known the feelings or views of such a man may be on his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters."/>
    
    <input type="submit" id="byBtn" value="Change" onclick="my_change()"/>
    <input type="button" id="refresh" value="Reset" onclick="my_remove()"/>
    
    <p id="title"></p>

    0 讨论(0)
  • 2021-01-21 19:23

    Ok, so first you need to break your input string value into an array.

    var myString = document.getElementById('myTextField').value;
    myString = myString.split(" ");
    

    Then you can compare the two arrays using for loops based on the length of each array. You will embed a for loop in a for loop like this:

    var matchingWords = document.getElementById("title");
    var match = 0;
    for (var i = 0; i < myString.length; i++) {
      for (var j = 0; j < matches.length; j++) {
        if (myString[i] == matches[j]) {
          match = 1;
          matchingWords.innerHTML += "<span style='color:blue'>" + " " + myString[i] + " " + "</span>";
        } else if ((j == matches.length - 1) && match === 0) {
          matchingWords.innerHTML += " " + myString[i];
        } //else if
      } // for j
    } // for i
    

    You will also need to set a trigger that basically says that has or hasn't been a match.

    If there is a match, set the match variable to 1 to nullify the else if. But, if there hasn't been a match and you are at the end of the inside loop then print the word without the special coloring.

    Check out this jFiddle I made for you. I hope this helps. https://jsfiddle.net/shbrantley/s0nc734p/78/

    Here is the full HTML:

    <input type="text" id="myTextField" value="his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters. " />
    <br>
    <input type="submit" id="byBtn" value="Change" onclick="change()" />
    <p id="title"></p>
    

    Here is the full javascript:

    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"];
    
    change = function() {
      var myString = document.getElementById('myTextField').value;
      myString = myString.split(" ");
      var matchingWords = document.getElementById("title");
      var match = 0;
      for (var i = 0; i < myString.length; i++) {
        for (var j = 0; j < matches.length; j++) {
          if (myString[i] == matches[j]) {
            match = 1;
            matchingWords.innerHTML += "<span style='color:blue'>" + " " + myString[i] + " " + "</span>";
          } else if ((j == matches.length - 1) && match === 0) {
          matchingWords.innerHTML += " " + myString[i];
          } //else if
        } // for j
        match = 0; // reset match
      } //for i
    } //change
    
    0 讨论(0)
  • 2021-01-21 19:26

    So what you could do is search the array of words and compare to the value. Your original code looked to see if the element was an array.

    (function() {
      'use strict';
    
      function change() {
        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"],
          myNewTitle = document.getElementById('myTextField').value,
          title = document.getElementById('title'),
          doesMatch = matches.reduce(word => myNewTitle.search(word) >= -1);
    
        if (doesMatch) {
          console.log('yes');
          title.style.color = 'green';
        } else {
          console.log('no match');
          title.style.color = 'red';
        }
    
        title.innerHTML = myNewTitle;
      }
    
    
      document.querySelector('#byBtn').addEventListener('click', change, false);
    }());
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Using Arrays to change color...</title>
    </head>
    
    <body>
    
      <input type="text" id="myTextField" value="his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters." />
      <input type="submit" id="byBtn" value="Change" />
      <p id="title"></p>
    
    </body>
    
    </html>

    0 讨论(0)
  • 2021-01-21 19:30

    This is just a guess, but why don't you try this

    This is assuming, you want to change the words, on the blur

    var input = document.getElementById("my-input");
    var par = document.getElementById("par");
    
    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"];
    
    input.addEventListener("blur", function() {
        var inputValue = input.value;
        par.innerHTML = "";
        inputValue.split(' ').forEach(function(word) {
            if (matches.indexOf(word) > -1) {
        	      par.innerHTML += "<span class='colored'>" + word + " " + "</span>";
            }
            else {
                par.innerHTML += word + " ";
            }
        });
    });
    .colored {
      color: blue;
    }
    <textarea id="my-input"></textarea>
    
    <p id="par"></p>

    0 讨论(0)
  • 2021-01-21 19:31

    I think you want something like this:

    change = function() {
      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"
      ];
    
      // get the current value of the "myTextField" element
      var myTextFieldValue = document.getElementById('myTextField').value;
    
      // split this string at every space character - we now have
      // an array of individual words
      var myTextFieldWords = myTextFieldValue.split(' ');
    
      // for each of these words, test if the "matches" array contains
      // the word.  If it does, surround it with a <span class="match"> tag.
      var formattedWords = myTextFieldWords.map(function(word) {
        if (matches.indexOf(word) !== -1) {
          return '<span class="match">' + word + '</span>';
        } else {
          return word;
        }
      });
    
      // formattedWords now looks like this:
      // ['<span>his</span>', 'first' 'entering', 'a' .... ]
      
      // join all the items in the formattedWords array (with a 
      // space between each word) into a single string, and set
      // it as the innerHTML of the #title element
      document.getElementById('title').innerHTML = formattedWords.join(' ');
    }
    .match {
      color: blue;
    }
    <input type="text" id="myTextField" value="his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters." />
    <input type="submit" id="byBtn" value="Change" onclick="change()" />
    <p id="title"></p>

    0 讨论(0)
提交回复
热议问题