What is the problem with using the string replace method in my typescript code?

Asked

Viewed 42 times

0

Good afternoon, you guys. I am using the Typescript language for the first time in a "weekend project" in developing an extension for Vscode. I’ve done research for the method documentation, but I still don’t understand where I’m going wrong. I imagine it’s a "silly" problem due to inexperience with language. What is happening is that the use of the string replace method is not actually replacing all strings taken from two vectors. The function removePalavrasSelectionCodigoPython is not removing all strings from a Python code snippet, also passed as a string by the selectedCodigo variable. Following the code:

function executaExtensaoPython(selecaoCodigo:string, formatoArquivo:string):void{
    var alfabetoPython : string[] = ["#", "selfie", ".", "=", "get", "set", "(", ")", ":", ","];
    var alfabetoIgnorar : string[] = [" "];
    var selecaoCodigoModificada;

    //Retirando palavras do alfabeto das linguagens Python e Ignorar
    selecaoCodigoModificada = retiraPalavrasSelecaoCodigoPython(selecaoCodigo, alfabetoIgnorar, alfabetoPython);
    console.log("\nSELEÇÃO MODIFICADA = " + selecaoCodigoModificada);
}
function retiraPalavrasSelecaoCodigoPython(selecaoCodigo : string, alfabetoIgnorar : string[], alfabetoPython : string[]) : string{
    for(var i=0;i<alfabetoIgnorar.length;i++){
        selecaoCodigo = selecaoCodigo.replace(alfabetoIgnorar[i], "");
    }
    for(var i=0;i<alfabetoPython.length;i++){
        selecaoCodigo = selecaoCodigo.replace(alfabetoPython[i], "");
    }
    return selecaoCodigo;
}

1 answer

2


The function removePalavrasSelecaoCodigoPython is replacing only the first occurrence of each element you want to remove. One way to replace all occurrences is to use split followed by Join:

function retiraPalavrasSelecaoCodigoPython(selecaoCodigo : string, alfabetoIgnorar : string[], alfabetoPython : string[]) : string{
    for(var i=0;i<alfabetoIgnorar.length;i++){
        selecaoCodigo = selecaoCodigo.split(alfabetoIgnorar[i]).join("");
    }
    for(var i=0;i<alfabetoPython.length;i++){
        selecaoCodigo = selecaoCodigo.split(alfabetoPython[i]).join("");
    }
    return selecaoCodigo;
}

For more details on this, see this reply: https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string

  • Thank you very much, Matheus.

Browser other questions tagged

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