How to search for words with javascript?

Asked

Viewed 6,557 times

2

Hi. I need to take the responseTxt I received from a page and search for elements in it. The elements I need to display are those coming from a tag called "name name".

Example:

In the file there are some lines of the type:

string(numero) = "nodo=""nome"

I need to find every place it’s written "nodo=" and pick up every word followed by it. In case, if 3 occurrences of "nodo=" and each has a word (e.g., one has stone, another paper and another scissors), I have to take these 3 occurrences of nodo= and take the words of each and print them on the screen.

  • Can you give a clearer example? these quotes are a little weird to have in a string "nodo=""nome"? joins the string you have pf.

  • It’s a response from a post. I post via ajax on a website and get responseTxt. But this responseTxt is how the site sends. I wanted to filter. He sends everything like this, as in the example. But there are some things that this written string and something out of context and others (the ones that I care about) is written "nodo name="""Document" ( or other words). I hope that’s clearer. I just want to search for words in responseTxt preceded by a "node name=", because those are the ones I want to print on the screen. Hug!

  • I don’t have here now the full string of responseTxt but it’s like this (the model) ... String(46)=> "name=""name"""/string" string (58)=> "node name=""document""/html" string (35)=>"age""40"""anything" string (43)=> "node name=""today"""something". Note: This is a model of how it is, Nap remember what is written in the other "string". I need to take the following word to "node name="

  • Luciano, for each string "string(n) => ..." has a line break?

  • Toby yes! There for 11 hrs~ 12 hrs I get home there put the answer given by the server on responseTxt. But each string (n) it prints as a line

  • Below is the server response (responseTxt), which I need to pick up only the words after Node name: Server response: array(173) { [0]=> string(10) "<Document>" [1]=> string(24) "<nodo name="background">" [2]=> string(10) "<id>1</id>" [3]=> string(34) "<occurrence>0.3115942</occurrence>" [4]=> string(23) "<relacoes name="image">" [5]=& ;string(23) "<connections>48</connections>" [6]=> string(11) "</relationships>" [7]=>

  • @Lucianozancan, could you update your question with Responsetext content? this type of information is not visible within a comment.

  • @Lucianozancan, updated the answer, take a look at it to see if it solves your problem.

  • Use a regular expression to search for patterns.

Show 4 more comments

3 answers

1


Hi, you can find a word using the index method');

The method will return the index of the searched word, in case, I believe it will be something like this:

var busca = "nodo=";
var indexBusca = seuRetorno.indexOf(busca);

To test if found just check the returned value, in case if it is different from -1 is that the word was located.

if (indexBusca != -1) {
    // seu código
}

Hugs.

  • Your answer has two problems. the first is that it returns only the first incidence of the text "Node=", the second is that the Questioner is not interested in this text, but rather in the value assigned to it.

0

You can use a regexp to do this:

Example:

I put in the middle of the text two expressions in the format you indicated to exemplify:

  • [1]=> string(24) "<nodo name="background">" [1243]=> string(24) "<nodo name="xpto">"

  • the result will be: ["background","xpto"]

var text = 'array(173) { [0]=> string(10) "<document>" [1]=> string(24) "<nodo name="background">" [1243]=> string(24) "<nodo name="xpto">" [2]=> string(10) "<id>1</id>" [3]=> string(34) "<ocorrencia>0.3115942</ocorrencia>" [4]=> string(23) "<relacoes name="image">" [5]=> string(23) "<conexoes>48</conexoes>" [6]=> string(11) "</relacoes>" [7]=>';

var items = text.split(/nodo name="([^"]*)"/g);
var count = items.length;
var result = [];
for (var i = 1; i < count; i += 2)
    result.push(items[i]);

document.getElementById("output").innerHTML = JSON.stringify(result)
<div id="output"></div>

It’s not the most performative form in the world, but it’s the easiest way to do it for me.

0

@Lucianozancan, based on his last example, I believe that Responsetext is a serialized XML document in an unconventional way.

In this case the interresante is to convert the Responsetext to an XML document and then work with the XML document:

Once we have the XML document, then we can search all tags nomes and retrieve the propriedade name of the same.

var responseText = '\
array(9) {\n\
    [0]=> string(10) "<document>"\n\
    [1]=> string(24) "<nodo name="background">"\n\
    [2]=> string(10) "<id>1</id>"\n\
    [3]=> string(34) "<ocorrencia>0.3115942</ocorrencia>"\n\
    [4]=> string(23) "<relacoes name="image">"\n\
    [5]=> string(23) "<conexoes>48</conexoes>"\n\
    [6]=> string(11) "</relacoes>"\n\
    [7]=> string(11) "</nodo>"\n\
    [8]=> string(11) "</document>"\n\
}\
';

var conteudoText = responseText.split("\n");
var conteudoXML =  [];
for (var indice in conteudoText) {    
    var text = conteudoText[indice];
    var indice = text.indexOf('"');
    if (indice >= 0) {
        var xml = text.substring(indice + 1, text.length - 1);
        conteudoXML.push(xml);
    }
}

var documentXML = new DOMParser().parseFromString(conteudoXML.join("\n"),"text/xml");

var nodos = documentXML.getElementsByTagName("nodo");
for (var indice = 0; indice < nodos.length; indice++) {
    var nodo = nodos[indice];
    console.log(nodo.getAttribute("name"));
}

EDIT: The solutions below were attempts to answer when the author of the question had not given enough data, I will keep them interesting.

If you want to work with plain text, you can find the occurrence of the text "Node name=" and then retrieve the next value that is in quotes.

var responseText  = '\
String (46)=> "name=""nome""/string" \
String (58)=> "nodo name=""documento""/html" \
String (35)=> "idade""40""qualquercoisa" \
String (43)=> "nodo name=""hoje""algoaqui" \
';

function encontrarValores(string, chave, separador, delimitador){
    var indice = string.indexOf(chave, 0);
    var valores = [];

    do {        
        
        var iniIndice = indice + chave.length + separador.length + delimitador.length;
        var fimIndice = string.indexOf(delimitador, iniIndice);
        var valor = string.substring(iniIndice, fimIndice);        
        valores.push(valor);
        indice = string.indexOf(chave, indice + 1);
      
    } while (indice >= 0);
    return valores;
}

var valores = encontrarValores(responseText, 'nodo name', '=', '""')
console.log(valores);

But if you were working with HTML, you could simply do the following:

var responseText  = '\
    <div nodo="externa">\
        <div nodo="interna 1">Interna 1</div>\
        <div nodo="interna 2">Interna 2</div>\
        <div nodo="interna 3">Interna 3</div>\
    </div">\
';

var container = document.createElement("div");
container.innerHTML = responseText;


var elements = container.querySelectorAll("[nodo]");
for (var indice in elements) {
    var element = elements[indice];
    if (element.nodeType == 1) {
        console.log(element.getAttribute("nodo"));
    }
}

  • Now that I’ve seen the author’s comment, I’ll add something useful to it.

Browser other questions tagged

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