如何在javascript中的特定子字符串后获取子字符串

时间:2016-04-03 01:39:22

标签: javascript bots

我正在制作一个机器人来自动回答琐事问题。我被困在这一点上。我有问题的字符串,我想从字符串中包含所有问题的问题。

在这个例子中,我有一个带有问题的字符串:

    var str="This was the first cartoon talking picture"

我有一个变量

    "Steamboat Willie"

我需要在问题的字符串中找到str的字符串并在*之后得到部分,所以

{{1}}

我真的不知道该怎么做。

3 个答案:

答案 0 :(得分:1)

假设您的字符串在每个问题和答案对之间使用换行符进行格式化:

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],你会得到你的答案!

答案 1 :(得分:1)

首先拆分问题,然后过滤它们,最后得到答案

var questions="This was the first 3-D film*Bwana Devil\nThis was the first cartoon talking picture*Steamboat Willie\nThis was the sequel to \"Star Wars\"*The Empire Strikes Back"
var str="This was the first cartoon talking picture"
    
var answers = questions
   .split("\n")
   .filter(question => question.indexOf(str) > -1)
   .map(question => question.substring(question.indexOf(str)+str.length+1))

alert(answers.join(","))

答案 2 :(得分:0)

for( int i =0; i < questions.lenght;i++)
{
    var string = questions.split("*")[i].substring(0,"\n");
}

这样的事情会起作用吗?