I wonder if I can modify a string inside an array without knowing its position

Asked

Viewed 54 times

-3

Ex:

const array=[...'indice n','indice n2',...]

After modifying:

array = [...'maçã','indice n2,...']

 function checkForTranslation(){
            var input = document.getElementById('inputTextField').value
            var outputDiv = document.getElementById('translationOutputDiv')
            input = input.toLowerCase();
            const newInput = input.split(space)
            var index = newInput.indexOf('hi')
            if(newInput.includes('hi')){
                outputDiv.innerHTML = `${input.replace(/hi/g, '')}`
            }

I know what’s inside the if doesn’t make much sense, but it’s because I haven’t found a solution yet, but basically I’m trying to make a Translate, but whenever the word is written to be translated into the sentence it when replaced by the translation goes to the end of the sentence, so I thought to transform the string into an array to change the word value inside the array and return to string.

  • 1

    what you tried and what’s failing? You have to post some code so we can help. Have a look https://answall.com/help/how-to-ask

  • I made a change to the question, please look if you can understand better

  • vc can use a foreach, find the value and replace it, or use map https://stackoverflow.com/questions/35206125/javascript-es6-es5-find-in-array-and-change/35206193

  • If you want to swap a word from a string, you may not need to transform into array: https://answall.com/q/16963/112052 | https://answall.com/q/506410/112052

  • You have to close that question until the author of it improves! The text is a question about replacing elements in an array, the example presented is about manipulating HTML code. This is unfair to authors of answers because it implies that for those who answer it is subject to be negative or to follow what is in the text of the question and contradict the code of the example or to be negative or to follow what is in the code of the example and contradict the text of question.

  • You interpreted the question totally wrong then friend, I just presented the script that happens to contain HTML elements, but the question was 100% focused on the array, no HTML

  • Your question is confused and poorly elaborated and the function checkForTranslation() does not display an evident array interaction.

  • "const newInput = input.split(space) "it here

  • Then edit the question and clarify and join a [MCVE].

  • 1

    To focus "100% on the array", you should take the whole "extra" part (like the getElementById and innerHTML, that depend on an HTML to test) and leave only the array itself. In fact, the problem itself is "how to replace words in a sentence" - the array is just the way you tried, but it’s not the only one (focusing on the problem instead of focusing on the solution attempt might be better for opening up more solution possibilities: for example, if the phrase is "Hi, all right" and you want to change the "Hi", it won’t work because the split will separate "Hi," instead of just "Hi" - I don’t know if this applies to your case)

  • I’m not really used to programming, let alone asking questions at stackoverlfow, so I didn’t know I had to follow so many protocols, I came up with a question and I was greeted with stone here, for more than one time.

  • 1

    At first it’s hard to get the hang of it anyway, but in time you get it. Remember that the idea of the site is that the questions are useful not only for you, but for any future visitor with the same problem. Hence we are a little "boring" and "rigid" with the format, because the focus is on the specific problem (in your case, replace words in a sentence, regardless of whether or not an HTML is involved), without "distractions" and "wrinkles". That said, an alternative without array: https://ideone.com/M4WbmQ

  • thanks friend, I tried to implement what Voce sent me but as I will use other translations in a sentence for now this way: var index = newInput.forEach(function cada(item, indice){
 if(item == 'da'){
 newInput[indice] = 'good' 
 }
 
 });

Show 8 more comments

3 answers

-3

One of the options if you know what value you are looking for within this array is to go through the array to find the desired value and replace it.

Function to go through the array and change the desired value.

function alter (array, value1, value2) {
    for (let i = 0; i < array.length; i++ ) {
        if (array[i] === value1) {
          array[i] = value2;
          return;
        }   
    }
return;
}

Example of use of the function.

let array = ['indice 1', 'indice 2', 'indice 3']
console.log(array); // ["indice 1", "indice 2", "indice 3" ]
alter(array, 'indice 2', 'maça');
console.log(array) // [ "indice 1", "maça", "indice 3" ]

-3

function checkForTranslation(){
            var input = document.getElementById('inputTextField').value
            var outputDiv = document.getElementById('translationOutputDiv')
            input = input.toLowerCase();
            const space = ' ';
            const newInput = input.split(space)
            if (newInput.indexOf('hi') >= 0) {
            var index = newInput.indexOf('hi')
            newInput[index] = 'oi'
            console.log(newInput)
            const finalInput = newInput.join(' ');
            outputDiv.innerHTML = finalInput
            }

I don’t know if I turned around too much but in the end it worked right, thanks guys

  • There is a catch: if the word occurs more than once in the sentence, you only replace the first occurrence

  • is just discovered this problem ae, trying to solve

  • Then improve the question, because if reopened I guarantee that your question has the potential to receive quality answers far above the ones you have been receiving. Present a [mcve] where anyone can test it, set the substitution parameters and limits, Focus on the think-your-problem array in a more generic way where anyone in the future who has a problem similar to yours can turn to your question and the answers to your question for solution by making as few modifications as possible.

-3


The most coherent way would be to create a prototype, so you can use the function in local verios in a simple way.

 Array.prototype.replaceAll = function (oldValue, newValue){
         for(var i = 0; i <= this.length;i++){
                      var index = this[i]?.toLowerCase().indexOf(oldValue.toLowerCase());
            if(index == 0){
                    this[i] = this[i].replace(oldValue, newValue)
            } 
        }
       return this;
}

function checkForTranslation(){
     var input ="Morango é uma fruta vermelha assim como a managa é amarela";
     const newInput = input.split(" ")
     var novoValor = newInput.replaceAll("morango", "maça");
     console.log(novoValor)
     console.log(novoValor.join(' '))
}
  • 3

    When changing the prototype of any object, care should be taken with the prototype Pollution: https://answall.com/q/449732/112052

Browser other questions tagged

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