I'm trying to have my event listener on my input catch single words from one array and multi word phrases from another and capitalize the first letter of each word for them.

I've setup an event listener for an input. I previously added some code that checked as a user is typing in the input text box for any occurrences of the words found in my "words" array. If it finds one it auto-capitalizes it.

I then added a second array, "phrases" which I also want to automatically capitalize the words that are typed into the input box from this array. For example, if a user types into the input "automations shortcuts", it should be capitalized to "Automations Shortcuts" (this needs to account for any number of words in each phrase and capitalize the first letter of each).

I'm having trouble coding out the logic for this and getting phrases to properly be recognized and have each word in the phrase capitalize its first letter.

I'd really appreciate the help to figuring out how to accomplish this!

let inputBox = document.getElementById("ltext");

let words = ['automation', 'action', 'conditions', 'favorites'];
let phrases = ['automation places', 'another phrase with multiple words'];

inputBox.addEventListener("input", function() {
  //console.log("working");
  let string = this.value.toString();
  string = string.split(' ');
  for (let i = 0; i < string.length; i++) {
    let indexOf = words.indexOf(string[i]);
    if ((indexOf) > -1) {
      //console.log(indexOfPhrase);
      let uppercaseWord = words[indexOf].toString();
      string[i] = uppercaseWord.toLowerCase().split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1)).join(' ');
    }
  }
  string = string.join(' ');
  this.value = string;
});
<input id="ltext" />

1

There are 1 best solutions below

3
mplungjan On

Here is a set of replaces that are simpler than what you had

You do not even need two arrays

const titleCase = str => str.toLowerCase().replace(/\b\w/g, s => s.toUpperCase())
const makeRegex = str => new RegExp("\\b" + str + "\\b", "gi");
const inputBox = document.getElementById("ltext");

const words = ['automations?', 'actions?', 'conditions?', 'favorites?'];
const phrases = ['automation places?', 'another phrase with multiple words'];

inputBox.addEventListener("input", function() {
  let string = this.value; // always a string
  phrases.forEach(phrase => string = string.replace(makeRegex(phrase), s => titleCase(s)));
  words.forEach(word => string = string.replace(makeRegex(word), s => titleCase(s)));
  this.value = string;
});
<input id="ltext" />