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

标签 javascript bots

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

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

    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/

相关文章:

javascript - 当将 dropzone 与 browserify 一起使用时, $(...).dropzone 不是一个函数

javascript - 是否有可能知道 jquery 可拖动元素将恢复到哪里?

javascript - 如何使用Javascript替换不规则字符串前缀?

javascript - 如何使图标与文本左侧分开?

Python-属性错误: 'function' object has no attribute 'author'

python - 维基链接(irc 机器人)

javascript - 如果已选中所选框,如何在加载页面时运行 onchange 函数

javascript - 从 javascript 数组中选择一个随机项

java - 使用 java 扫描器解析文本文件

java - Discord JDA - 无效的成员列表