Using Replace With for Returning Last Value of an Array

- 1 answer

Ad

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.

Ad

Answer

Ad

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>

Ad
source: stackoverflow.com
Ad