1

I have a for loop in part with an array inside an object. It replaces, but it will only change the word(s) that are at the back of the array.

<textarea id='inp'></textarea>
<button onClick='rd()'>
k m8
</button>
<div id='res'>
</div>

<script>
var rd = function() {
var rep = "";
var inpt = document.getElementById('inp').value;
    for (i = 0; i < dict.before.length; i++) {
    var rep = inpt.replace(dict.before[i],dict.after[i]);
  }
  document.getElementById('res').innerHTML = rep;
}

var dict = {
    before : ["for","to","too"],
  after : ["4","2","2"]
}
</script>

If at the end of the before array, the value was "this" and after would be "that", all the other strings in each array would not work, they do not replace.

1 Answer 1

1

That is because you are overwriting the rep variable in each iteration of the for loop. You can simply perform replacement using the original init, i.e., change this line:

 var rep = inpt.replace(dict.before[i],dict.after[i]);

…to this line:

inpt = inpt.replace(dict.before[i],dict.after[i]);

And use the replaced inpt to set the innerHTML: document.getElementById('res').innerHTML = inpt;

See working example below:

var rd = function() {
  var rep = "";
  var inpt = document.getElementById('inp').value;
  for (i = 0; i < dict.before.length; i++) {
    inpt = inpt.replace(dict.before[i], dict.after[i]);
  }
  document.getElementById('res').innerHTML = inpt;
}

var dict = {
  before: ["for", "to", "too"],
  after: ["4", "2", "2"]
}
<textarea id='inp'></textarea>
<button onClick='rd()'>
  k m8
</button>
<div id='res'>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

The problem is it only replaces once, and when it should replace after it, it doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.