简体   繁体   中英

How to get substring after specific substring in javascript

I am making a bot to automatically answer to trivia questions. I am stuck at this point. I have the string of the question and I want to estrapolate it from the string with all the question of the Trivia.

In this example case, I have the string with the questions:

    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`

I have a variable

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

And I need to find the string of str in the string with the question and get the part after the *, so

    "Steamboat Willie"

.

I really don't know how to do it.

Assuming that your string is formatted with newlines between each question and answer pair:

1. Split the entire string by each newline:

var questionAnswerStringPairs = string.split('\\n');

This will create an array of questions and answer strings. Each answer will be separated by an '*'.

2. Map over the resulting array, and create matching objects:

// 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;
});

Now, you can do this: questionAnswerPairs['question i want the answer to'] , or this: questionAnswerPairs[stringObjectWithQuestion] and you will get back your answer!

First split the questions, then filter them and finally get the answer

 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");
}

Would something like this work?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM