Reputation: 59
Hopefully someone can help me.
when im input: "my name is jack".
Ouputput can display change: "my name is clara".
jack change with clara.
but when im input: "my name is toni"
Ouputput still display: "my name is toni"
that text "toni" can't change with "ana"
what's wrong with my code?, this my code
<html>
<body>
Enter Text: <input type="text" id="myText">
<button onclick="myFunction()">Replace</button>
<p id="check"></p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
var y = x.replace("toni", "ana");
document.getElementById("check").innerHTML = y;
var z = x.replace("jack", "clara");
document.getElementById("check").innerHTML = z;
}
</script>
</body>
</html>
sorry for my bad english
Thankyou...
Upvotes: 1
Views: 175
Reputation: 21485
Let's take this line by line:
var x = document.getElementById("myText").value;
X now contains the original text value, with no replacements.
var y = x.replace("toni", "ana");
Y contains the original text value with "toni" replaced by "ana".
document.getElementById("check").innerHTML = y;
You place Y inside the document.
var z = x.replace("jack", "clara");
That was the bug. Z contains the original text value with "jack" replaced by "clara". Note that this ignores the replacement you did in Y.
document.getElementById("check").innerHTML = z;
Now you place Z inside the document (overwriting the change you made earlier).
A simple way to resolve your issue without substantially rewriting your code would be to drop all the unnecessary intermediate variables, and do all the replacements on the same string before placing it back in the DOM:
var x = document.getElementById("myText").value;
x = x.replace("toni", "ana");
x = x.replace("jack", "clara");
document.getElementById("check").innerHTML = x;
Upvotes: 1
Reputation: 5316
You can create your own function, to define original and new names into arrays and match them:
<html>
<body>
Enter Text: <input type="text" id="myText">
<button onclick="myFunction()">Replace</button>
<p id="check"></p>
<script>
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function myFunction() {
var x = document.getElementById("myText").value;
var oldNames = ['toni', 'jack'];
var newNames = ['ana', 'clara'];
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
</script>
</body>
</html>
Upvotes: 1