首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于输入的事件侦听器检测和大写一个数组中的单个单词和另一个数组中的多个单词短语。

问用于输入的事件侦听器检测和大写一个数组中的单个单词和另一个数组中的多个单词短语。
EN

Stack Overflow用户
提问于 2022-10-29 18:43:53
回答 1查看 24关注 0票数 0

我试图让我的事件侦听器在我的输入中捕捉一个数组中的单个单词和另一个数组中的多个单词短语,并为它们大写每个单词的第一个字母。

我已经为输入设置了一个事件侦听器。之前,我添加了一些代码,当用户在输入文本框中输入" words“数组中出现的单词时,这些代码会被选中。如果它找到一个,它会自动大写它。

然后,我添加了第二个数组,“词组”,我也想要将输入框中输入的单词自动大写。例如,如果用户在输入的“自动快捷键”中键入“自动快捷键”,则应该将其大写为“自动快捷键”(这需要对每个短语中的任意数量的单词进行解释,并将每个短语的首字母大写)。

我很难写出这方面的逻辑,让短语被正确地识别,并让短语中的每个单词大写它的第一个字母。

我真的很感激你能帮我弄清楚如何做到这一点!

​

代码语言:javascript
复制
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;
});
代码语言:javascript
复制
<input id="ltext" />

​

EN

回答 1

Stack Overflow用户

发布于 2022-10-29 19:02:28

下面是一组比您所拥有的更简单的替换

您甚至不需要两个数组。

​

代码语言:javascript
复制
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;
});
代码语言:javascript
复制
<input id="ltext" />

​

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74247897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档