Remove part JavaScript String Informing the End

5

I have the following javascript function:

var opts = document.getElementById('id_endereco'); //localiza select
var str = opts.options[opts.selectedIndex].innerText; //Pega text do option

I need to remove part of the content of the select, 'str', this value is variable, but I have a fixed word in all options, the word is 'Address:'. I need to remove this word including everything that comes before it.

I tried:

var resultado_str = str.replace(0, str.indexOf("Endereço: ") + 1, "");
document.getElementById('endereco_correto').value = resultado_str;

But it did not work.

    
asked by anonymous 11.06.2015 / 03:42

1 answer

5

I made a combination of substring with indexOf , I get the index that starts "Endereço: " and I add to that index the number of characters that this text has, in case 10 .

var str = "texto antes Endereço: Da minha casa";
var textoReplace = "Endereço: ";
var resultado_str = str.substring(str.indexOf(textoReplace) + textoReplace.length); // essa soma da 22
  

"From my house"

Your problem with using indexOf is that it will return the first position of the text you entered, not the last as you expect.

Your final code will be:

var textoReplace = "Endereço: ";
var opts = document.getElementById('id_endereco'); //localiza select
var str = opts.options[opts.selectedIndex].innerText; //Pega text do option

var resultado_str = str.substring(str.indexOf(textoReplace) + textoReplace.length);
document.getElementById('endereco_correto').value = resultado_str;
    
11.06.2015 / 03:44