-1

I want to pass three variables to a function (the function is below), and the function should replace "Hahaha" by "Hohoho" but the Function displays "Hohaha" as result. I would like to use the /g global parameter. -How do I have to modify the function, so that the function returns "Hohoho" ?

myReplace("Hahaha","a","o");

function myReplace(s2,removeIt,insertIt) {
alert(s2.replace(removeIt,insertIt));
}
Heiko
  • 17
  • 1
  • 8
  • I wonder why 4 answers were posted about something that was already well-answered and deeply explained. – Al.G. Jul 17 '16 at 16:42
  • @Al.G. I had not realized this was a duplicate; your comment was after my answer. I have deleted the answer. Thanks for pointing it out. – Fengyang Wang Jul 17 '16 at 16:46
  • as Fengyang Wang stated: This question is not an exact duplicate of an existing question. – Heiko Jul 17 '16 at 17:56

1 Answers1

-1

Replace function only searched a string for a specified value and return a new string where the specified value are replaced.

If you want to replace a value not a regular expression only the first instance of the value will be replaced. To replace all occurrences use global modifier.

<!DOCTYPE html>
<html>
<body>



<p id="demo">hahahahaha</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace(/ha/g, "ho");
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>
Pirate
  • 2,886
  • 4
  • 24
  • 42
  • I want to have a function call like "alert(myReplace("Hahaha","a","o"))" -How do I have to modify this code: `myReplace("Hahaha","a","o"); function myReplace(s2,removeIt,insertIt) { alert(s2.replace(new RegExp(removeIt, 'g'), insertIt)); }` – Heiko Jul 17 '16 at 17:04
  • **This is the solution :** `alert(myReplace("Hahaha","a","o"));` `function myReplace(s2,removeIt,insertIt) {` `return s2.replace(new RegExp(removeIt, 'g'), insertIt);` `}` – Heiko Jul 21 '16 at 20:19