javascript - Using arrays to change color of certain words in an input box - Stack Overflow

So I'm working on a JSFiddle and I'm a little confused about something.I have an input box c

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 function When you click the button currently the text displayed in the box will just be displayed below it, but I want it to change the colors of the words that appear in my array to lets say the color blue. Any help would be appreciated, I'm very new to HTML/CSS/JS so sorry if some of my terminology is incorrect

MyHTML

 <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>

Javascript

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"];
//if a value from array matches a value from myTextField
    if (matches===document.getElementById('myTextField'))
    {
            //change color of said words
    }
       var myNewTitle = document.getElementById('myTextField').value;
       var title = document.getElementById('title');
       title.innerHTML = myNewTitle;
    }

/

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 function When you click the button currently the text displayed in the box will just be displayed below it, but I want it to change the colors of the words that appear in my array to lets say the color blue. Any help would be appreciated, I'm very new to HTML/CSS/JS so sorry if some of my terminology is incorrect

MyHTML

 <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>

Javascript

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"];
//if a value from array matches a value from myTextField
    if (matches===document.getElementById('myTextField'))
    {
            //change color of said words
    }
       var myNewTitle = document.getElementById('myTextField').value;
       var title = document.getElementById('title');
       title.innerHTML = myNewTitle;
    }

https://jsfiddle/hnfe3Lgk/

Share Improve this question edited Mar 2, 2016 at 22:33 Jon asked Mar 2, 2016 at 22:27 JonJon 12712 bronze badges 1
  • 1 Post your fiddle as well. – Victory Commented Mar 2, 2016 at 22:28
Add a ment  | 

5 Answers 5

Reset to default 2

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>

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>

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>

So what you could do is search the array of words and pare 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>

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 pare 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/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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745290393a4620821.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信