Change part of Pattern or regex javascript dynamically

Asked

Viewed 46 times

-1

I am making an ajax request that will return me an "X" page. My goal is to cut the page and manipulate the outerHTML to return only the <tr> which correspond to a specific Pattern/regex.

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var body = this.responseXML.body.outerHTML;
    var main = body.slice(body.indexOf("<main"), body.indexOf("</main>"));
    var regex = /<tr[^>]*>(?:(?!<|AQUI)[\s\S])*(?:<(?!\/?tr)[^>]*>(?:(?!<|AQUI)[\s\S])*)*AQUI[\s\S]*?<\/tr>/gi;

    if(regex.test(main)) {
      var matches = main.match(regex);
      $('#resposta').html('<p class="result">Os ramais relacionados à <strong>' + setor + '</strong> são:');
      for(i = 0; i < matches.length; i++){
        $('#resposta').append(matches[i]);
        $('#resposta').append('<p class="more"><a href="intranet/ramais">Para mais detalhes acesse os Ramais do TJPB</a></p>');
      }
    } else {
      $('#resposta').html('Nenhuma combinação encontrada');
    }
  }
};

xmlhttp.open("GET",url, true);
xmlhttp.responseType = "document";
xmlhttp.send();

The pattern is working perfectly, only it’s static. The point is, I can’t manipulate it, change it:

/<tr[^>]*>(?:(?!<|AQUI)[\s\S])*(?:<(?!\/?tr)[^>]*>(?:(?!<|AQUI)[\s\S])*)*AQUI[\s\S]*?<\/tr>/gi

Where has AQUI would like to change the value dynamically according to a parameter. Let’s assume that I need to change to "abcd" or "efgh", for example.

ps. the url variable is previously populated and returns the page url

  • You can use the object new RegExp(textoExpReg, 'gi'), with the regular expression string passed to it being manipulated dynamically.

  • 1

    Obg by suggestion. I was already on that track, but what really solved was the attention to the escape of the Pattern to the bars etc. Obg

1 answer

1

For registration. I was able to solve as follows:

  1. I left Pattern as string
  2. I created a variable with a new Pattern for dynamic replace
  3. I executed a string replace by passing the dynamic value in val
  4. And the rest stayed pretty much the same

Important is to be aware that treating Pattern as a string you need to escape from "" using " ". And the final gmi rule is inserted in the new Regexp.

var pattern = '<tr[^>]*>(?:(?!<|CODE)[\\s\\S])*(?:<(?!\\/?tr)[^>]*>(?:(?!<|CODE)[\\s\\S])*)*CODE[\\s\\S]*?<\\/tr>';
var rgxreplace = /CODE/gmi;
pattern = pattern.replace(rgxreplace,val);
var newRegex = new RegExp(pattern,'gmi');

Browser other questions tagged

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