我想创建一个文本框,用户可以使用它来搜索英语单词的西类牙语等效项。但他们不能只输入单词,而是必须输入整个问题。
示例: 用户输入:“Man 用西类牙语怎么说?”预期输出:“你说 Hombre。”
我正在使用 switch 语句,因为用户还可以询问其他事情。如何在 switch case 中使用正则表达式来搜索用户想要了解其含义的单词,并将其替换为西类牙语等效项?
我知道如何使用正则表达式将句子的第五个单词(在上面的情况下为“man”)替换为“hombre”。但是由于用户可以询问“man”以外的单词,我该怎么做才能用许多西类牙语单词之一替换第五个单词,具体取决于第五个单词实际上是什么?
我希望我说得足够清楚,让您能够理解。
这就是我所拥有的:
function myFunction() {
var text;
var words = document.getElementById("myInput").value.toLowerCase();
switch(words) {
case "hello":
text = "Hello, my friend.";
break;
case "how do you say xxx in spanish?":
text = "You say yyy.";
break;
default:
text = "I don't know what you mean...";
}
document.getElementById("answer").innerHTML = text;
}
function translate() {
var str = document.getElementById("answer").innerHTML;
var txt = str.replace("yyy","*spanish word*");
document.getElementById("answer").innerHTML = txt;
}
<p>Ask for the Spanish equivalent of an English word.</p>
<input id="myInput" type="text" size="50">
<button onclick="myFunction();translate()">Ask</button>
<p id="answer"></p>
我希望能够检测用户在 xxx 的位置输入的单词,并在答案中使用该单词的西类牙语等效词,这意味着我还需要有一种方法来告诉 man=hombre , 女人=mujer, child =niño...
我对如何实现这一目标有点迷失。有什么帮助吗?
最佳答案
如果您希望每次都要求句子的措辞完全一样,您可以使用表达式 /how do you say\w+ in spanish\?/i
来匹配输入和表达式 /say (\w+)/i
捕获要翻译的单词。
function myFunction() {
var text;
var words = document.getElementById("myInput").value.toLowerCase();
if (words === "hello") {
text = "Hello, my friend.";
} else if (words.match(/how do you say \w+ in spanish\?/i)) {
// matched word is the second element
var word = words.match(/say (\w+)/i)[1];
// find the translation in the object
var translation = lookup[word];
text = "You say " + translation + ".";
} else {
text = "I don't know what you mean...";
}
document.getElementById("answer").innerHTML = text;
}
var lookup = {
hello: "hola",
goodbye: "adios"
}
<p>Ask for the Spanish equivalent of an English word.</p>
<input id="myInput" type="text" size="50">
<button onclick="myFunction()">Ask</button>
<p id="answer"></p>
要翻译该单词,您可以构建一个映射到西类牙语单词的英语单词对象,因为您说过总共只有 20 个单词。
关于Javascript - 搜索和替换特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52628452/