Exercise: Quick replacement

Asked

Viewed 140 times

-1

Your mission now is to create a function called substituicaoRapida that you receive a text, a word to look for and the word that will replace the one you are looking for. The function should return the text with the word replaced.

Example:

let textoNovo = substituicaoRapida('Boa tarde','tarde','noite');
console.log(textoNovo) //'Boa noite'

When calling the function substituicaoRapida("Olá, usuário!","usuário","Ana") should return "Hello, Ana!"

As I did:

function substituicaoRapida ( ){
let texto = "Boa tarde"
let palavra = "tarde"
let textoNovo = texto.replace("tarde", "noite")
console.log(texto + ", " + palavra + ", " + textoNovo)
return textoNovo
}
substituicaoRapida ( )
  • Important you [Dit] your post and explain the problem by describing what you tried and where is the current difficulty, preferably with a [mcve]. Studying the post available on this link can make a very positive difference in your use of the site: Stack Overflow Survival Guide in English

4 answers

1

To meet the requested situation, just use the function below:

Note: The above function only replaces the first occurrence of the string, so it will not meet the cases where the word to be replaced occurs more than once in the string.

function substituicaoRapida(texto, procurar, substituir){
  return texto.replace(procurar, substituir);
}

let textoNovo = substituicaoRapida('Boa tarde','tarde','noite');
console.log(textoNovo) //'Boa noite'

let textoMaisOcorrencias = substituicaoRapida('Boa tarde? Sim, boa tarde!','tarde','noite');
console.log(textoMaisOcorrencias) //'Boa noite? Sim, boa tarde!'

To meet all occurrences, use the method below, which as its name says, is less performative than the previous method:

   function substituicaoLenta(texto, procurar, substituir){
      return texto.split(procurar).join(substituir);
    }

    let textoNovo = substituicaoLenta('Boa tarde','tarde','noite');
    console.log(textoNovo) //'Boa noite'

    let textoMaisOcorrencias = substituicaoLenta('Boa tarde? Sim, boa tarde!','tarde','noite');
    console.log(textoMaisOcorrencias) //'Boa noite? Sim, boa tarde!'

I hope I’ve helped!

1

A first problem is that you stated function substituicaoRapida ( ), that is, the function does not receive any parameter. And inside it, you always use the same text ("Good afternoon"), so no matter what you pass to the function, it will always use this text.

Therefore, its function should receive the texts as parameters, instead of always having a fixed text within it:

function substituicaoRapida(texto, antigo, novo) {
    return texto.replace(antigo, novo);
}

console.log(substituicaoRapida('Boa tarde!', 'tarde', 'noite')); // Boa noite!
console.log(substituicaoRapida('Olá, usuário!', 'usuário', 'Ana')); // Olá, Ana!

Thus, the function receives the original text, the passage to be replaced and the new text. But it has two poréns:

The first is that the replace is only done once. So if there is more than one occurrence of the word, only the first is replaced:

function substituicaoRapida(texto, antigo, novo) {
    return texto.replace(antigo, novo);
}

console.log(substituicaoRapida('Boa tarde! Já é tarde.', 'tarde', 'noite')); // Boa noite! Já é tarde.

The above code prints "Good night! It’s late." as only the first occurrence of "late" was replaced by "night".

The other however - it is not clear if it is something that should be considered in your code (although not even the case of replacing only the first occurrence is specified, but anyway) - is that the replace does not take into account whether the text to be replaced is actually part of a word or whether it should be only an entire word. Ex:

function substituicaoRapida(texto, antigo, novo) {
    return texto.replace(antigo, novo);
}

console.log(substituicaoRapida('Entardeceu', 'tarde', 'noite')); // Ennoiteceu

The code above prints "Ennoiteceu".

Anyway, if you want to take into account the 2 cases above, just use a regular expression, using RegExp:

function substituicaoRapida(texto, antigo, novo) {
    return texto.replace(new RegExp(`\\b${antigo}\\b`, 'g'), novo);
}

console.log(substituicaoRapida('Boa tarde, é tarde. Entardeceu', 'tarde', 'noite')); // Boa noite, é noite. Entardeceu

The code above prints "Good night, it’s night. Dusk" (the two occurrences of "afternoon" were replaced by "night", and "Dusk" is not replaced by the word "late").

Basically, I used the shortcut \b, that indicates a "boundary between words" (a position that contains an alphanumeric character before and a non-alphanumeric character after, or vice versa), so I guarantee that it will only take the word "afternoon", and ignore when it is part of another word (as in "Dusk"). Remembering that by being in a string, the character \ should be written as \\. Here you can see more details about the \b.

I also use the flag g (the second parameter in the RegExp), which causes all occurrences to be replaced (not only the first).

0

Note that when returning textoNovo the script finishes its execution by returning the new variable value textoNovo, however it does nothing with this value, does not print on the console.

This way to print this new value in the console at the end of the script use:

function substituicaoRapida()
{
    let texto = "Boa tarde"
    let palavra = "tarde"
    let textoNovo = texto.replace("tarde", "noite")
    return console.log(textoNovo)
}
substituicaoRapida ( )

0

Let’s understand what the function replace does? the function takes two parameters the first for search and the second for substitution


let nome = "noite"
console.log(nome.replace("noite", "dia"))

note that this function does not change the original variable

console.log(nome)

so we should assign the other or the same variable

nome = nome.replace("noite", "dia")
console.log(nome)

His exercise: Your mission now is to create a function called "replacementRapida" that you receive a text, a word to search and the word that will replace the one you are looking for. The function must return the text with the replaced word.

the first function option and I like this option more would be used Arow functions

let nomeAntigo = "nomeAntigo"
const trocaNomes = (nome, novoNome) => nome.replace(nome, novoNome)
nomeAntigo = trocaNomes(nomeAntigo, "nomeNovo")
console.log(nomeAntigo)

The second form would be using a more conventional language function

function substituicaoRapida() {
    let texto = "Boa tarde"
    let textoNovo = texto.replace("tarde", "noite")
    return (`${textoNovo}`)
}

console.log(substituicaoRapida('Boa tarde'))

Browser other questions tagged

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