Remove Part String Javascript Informing the End

Asked

Viewed 6,281 times

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 from select, 'str', this value is variable, but I have a fixed word in all options, the word 'Address: '. I need to remove this word including everything that comes before it.

I tried to:

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

But it didn’t work.

1 answer

5


I made a combination of substring with the indexOf, I get which index the "Endereço: " and we add to this 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

"Of my house"

Your problem with using indexOf is that it will return the first position of the informed text and not the last as you are expecting.

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;
  • The point is I need to clear the words that come before the 'Address: ', and keep the rest.

  • @sNniffer I understood your problem, updated the answer with the new solution.

  • Ball show, worked very well, thank you

Browser other questions tagged

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