How to extract a specific text from a string via Javascript

Asked

Viewed 843 times

1

Question related to how to remove only part of the text that is after my tags p: and r:

I am developing an application similar to chatbot simsimi and for test questions I am storing the questions and answers in a var within the script. So that the bot can learn new questions and answers, I’m trying to create a command where the user would send the question and answer through the use of tags p: and r: as in the example below:

Example:

var text = "p: pergunta r: resposta"

For this I would have to take only the content inside my tags but do not know how to do it. Via .indexOf() I even tried but I don’t know how to limit what he picks up until the beginning of the next tag.

3 answers

0

for the answer

text.substr((text.search(/r:/)+2))

to the question

text.substr((text.search(/p:/)+2),(text.search(/r:/)-2))
  • if it is like in the example, if it is in a scenario where you do not know how it will arrive (with words before p:) it is best to cut the string

  • to solve this I created an if where it would only be accepted if the order were p: and r: respectively, where the p: would have to be at the beginning of the message.

0

  • Yes, the problem is that the question and the answer would be in the input where the messages are sent

0


You can use a Regexp to extract these question/answer pairs.

It could be something like this:

var texto = "p: perguntaA r: respostaA p: perguntaB r: respostaB p: perguntaC r: respostaC";
var regex = /((\w:\s?)([^:]+)\s(\w:\s?)([^:]+)(\s|$))/g;
var pares = [], match;
while (match = regex.exec(texto)) {
    pares.push({
        p: match[3],
        r: match[5]
    });
}
console.log(pares);

You can see the regex working here: https://regex101.com/r/I8yCcg/1 but the idea is:

  • a "super group" catching, with two equal groups inside
  • (\w:\s?) refers to p: or r:
  • ([^:]+) means "something except ;"
  • and after that group \s or $ to ensure there is a gap or end of line before the next match.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.