Using Replace With for Returning Last Value of an Array
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
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad