Last position of a string

2

I have the following code:

 var elements = document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
     var txt = elements[i].innerHTML.replace('Estoque1', 'Estoque Vencido');
    }

It captures all page tags, and changes the word Inventory1 to Stock Expired. I need to make a code that it delete everything that is below the word "Stock Expired" after the word has been changed. In case, if it was in delphi I would use lastpos , now in JavaScript I have no idea, can anyone help me?

    
asked by anonymous 18.06.2014 / 16:09

2 answers

1

With the use of regular expressions you can do this:

  
var txt = "Foo Bar Estoque1 Baz Poo Par Paz...";
txt = txt.replace(/Estoque1(.*)/, "Estoque Vencido");
// => Foo Bar Estoque Vencido

The function laspos ( or LastDelimiter ) Delphi can be considered equivalent to Javascript lastIndexOf() .

  
var elementos = document.querySelectorAll('body *');
for (var indice = 0; indice < elementos.length; indice++)
{
   var txt = elementos[indice].innerHTML;
   var last = txt.lastIndexOf('Estoque1'); 
   if(txt.indexOf('Estoque1') > -1)
   {
      txt = txt.substring(0, last) + "Estoque Vencido" + txt.substring(last + txt.length);
      elementos[indice].innerHTML = txt;
   }
}

Fiddle

    
18.06.2014 / 18:37
2

You could use the .slice() JavaScript function, so your code looks like this:

var elements = document.querySelectorAll('body *');
 for (var i = 0; i < elements.length; i++){
     var txt = elements[i].innerHTML;

     //Só dispara as alterações caso o conteúdo contenha a palavra "Estoque1"
     if(txt.indexOf('Estoque1') > -1){
         txt = txt.replace('Estoque1', 'Estoque Vencido');
         txt = txt.slice(0,15);
         elements[i].innerHTML = txt;
     }
 }

I also substitutes .getElementsByTagName() by .querySelectorAll() for better operation.

Example: FIDDLE

    
18.06.2014 / 18:33