I have a controlled <input />
in my React application where the user would type.
I want to keep track on it and replace the occurrences of $.text
and $.lang
to random hashes/number.
from
let string = 'I may have multiple $.text and $.lang like $.textand$.lang';
I want all occurrences of $.text and $.lang to have a random number(or anything unique):
to
updatedString = 'I may have multiple 123 and 245 like 744and111';
What I have done so far
let temp = value.split('').reverse().join(''); // reverse it to find the latest occurrence let reText = /txet.$/i; let reLang = /gnal.$/i; let updated; if (value.includes('$.text')) { updated = temp.replace(reText, `${hash}#`); // replace the latest occurrence } else { updated = temp.replace(reLang, `${hash}#`); // replace the latest occurrence } updatedValue = updated.split('').reverse().join(''); // re reverse it
The issue is it replaces the but onChange RESETS the input state and it only changes the last occurrence of it.
Advertisement
Answer
So im doing it on click. So lets say user type something and then clicking on Replace Template
button will replace the $.text
and $.lang
by some random number. You can insert your specific hash or number if needed.
const replaceTemplateByRandom = (val, temp) => { while(val.indexOf(temp) != -1){ const numb = Math.floor(Math.random()*1000); val = val.replace(temp, numb); } return val; }
inside this arrow function I’m running the while loop till we find the template to replace, and replace occurrence by random number.
const replaceTemplateByRandom = (val, temp) => { while(val.indexOf(temp) != -1){ const numb = Math.floor(Math.random()*1000); val = val.replace(temp, numb); } return val; } function App(props){ const [val, setVal] = React.useState('default text is $.text, and language is $.lang.'); const updateVal = (e) => { const newVal = e.target.value; setVal(newVal); } const replaceTemplate = ()=>{ let currentVal = val; currentVal = replaceTemplateByRandom(currentVal, '$.text'); currentVal = replaceTemplateByRandom(currentVal, '$.lang'); setVal(currentVal); } return <div> <input type="text" value={val} onChange={updateVal} style={{"width":"100%"}}/> <button onClick={replaceTemplate}>Replace Template</button> </div>; } ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script> <div id="app"></div>