我正在制作一个自动回答琐事问题的机器人。我被困在这一点上。我有问题的字符串,我想将它从包含琐事的所有问题的字符串中分离出来。
在这个例子中,我有带有问题的字符串:
var questions=`This was the first 3-D film*Bwana Devil
This was the first cartoon talking picture*Steamboat Willie
This was the sequel to "Star Wars"*The Empire Strikes Back`
我有一个变量
var str="This was the first cartoon talking picture"
而我需要在有问题的字符串中找到str的字符串,得到*后面的部分,所以
"Steamboat Willie"
.
我真的不知道该怎么做。
最佳答案
假设您的字符串在每个问题和答案对之间使用换行符格式化:
1。用每个换行符拆分整个字符串:
var questionAnswerStringPairs = string.split('\n');
这将创建一个问题和答案字符串数组。每个答案将以“*”分隔。
2。映射结果数组,并创建匹配的对象:
// This will store our data.
var questionAnswerPairs = {};
// Let's go through each string from step one and add the question and
// its answer to our object.
questionAnswerStringPairs.forEach( function(pair) {
// split the string at the *
pair = pair.split('*');
// pair is now an array, the first element is the question string
// the second element is the answer. Let's set those!
var question = pair[0];
var answer = pair[1];
// now let's store that info in the object.
questionAnswerPairs[question] = answer;
});
现在,您可以这样做:
questionAnswerPairs['question i want the answer to']
,或者这样:questionAnswerPairs[stringObjectWithQuestion]
,你会得到你的答案!
关于javascript - 如何在javascript中获取特定子字符串后的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36380711/