How to extract specific text from a string via JavaScript

1

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

I'm developing an application similar to chatbot simsimi and for testing purposes I'm storing the questions and answers in a var within the script. In order for the bot to learn new questions and answers, I'm trying to create a command where the user would send the question and answer using the p: and r: tags as in the example below:

Example :

var text = "p: pergunta r: resposta"

For this I would only have to get the content inside my tags but I do not know how to do it. I've seen% I've even tried but I do not know how to limit what it takes until the beginning of the next tag.

    
asked by anonymous 29.04.2017 / 04:21

3 answers

0

You can use 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: link but the idea is:

  • a "super group" capture, with two equal groups within
  • (\w:\s?) refers to p: or r:
  • ([^:]+) means "something other than ; "
  • and after that group \s or $ to ensure there is a space or end of line before the next match.
29.04.2017 / 08:52
0

for the answer

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

for the question

text.substr((text.search(/p:/)+2),(text.search(/r:/)-2))
    
29.04.2017 / 04:46
0

I recommend that you use 2 inputs, one for the question and one for the answer. We have to always wait for the user to do it the wrong way, ie, do not put the "p:" and the "r:" correctly, put it.

Create 2 inputs and then take what has been typed in them. Here are examples if you want to use JS: link

And here using JQuery:

var text= $('#input_name').val();
    
29.04.2017 / 06:14