我试图让我的事件侦听器在我的输入中捕捉一个数组中的单个单词和另一个数组中的多个单词短语,并为它们大写每个单词的第一个字母。
我已经为输入设置了一个事件侦听器。之前,我添加了一些代码,当用户在输入文本框中输入" words“数组中出现的单词时,这些代码会被选中。如果它找到一个,它会自动大写它。
然后,我添加了第二个数组,“词组”,我也想要将输入框中输入的单词自动大写。例如,如果用户在输入的“自动快捷键”中键入“自动快捷键”,则应该将其大写为“自动快捷键”(这需要对每个短语中的任意数量的单词进行解释,并将每个短语的首字母大写)。
我很难写出这方面的逻辑,让短语被正确地识别,并让短语中的每个单词大写它的第一个字母。
我真的很感激你能帮我弄清楚如何做到这一点!
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" />
发布于 2022-10-29 19:02:28
下面是一组比您所拥有的更简单的替换
您甚至不需要两个数组。
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" />
https://stackoverflow.com/questions/74247897
复制相似问题