簡體   English   中英

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

[英]How to get substring after specific substring in javascript

我正在制作一個自動回答瑣事問題的機器人。 我被困在這一點上。 我有問題的字符串,並且我想從所有瑣事問題的字符串中推斷出它。

在此示例中,我有以下問題的字符串:

    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"

我需要在字符串中找到帶有問題的字符串,並在*后面獲取部分,因此

    "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] ,您將獲得答案!

首先拆分問題,然后過濾它們,最后獲得答案

 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(",")) 

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

這樣的事情行嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM