1

in javascript the following is returning an error saying that hello.replaceAt is not a function, that hello.replaceAt is undefined.

    var hello = 'Hello World';
    alert(hello.replaceAt(2, "!!"));

Why is this not working? Thanks.

Paul
  • 1,277
  • 5
  • 28
  • 56
  • 4
    replace is a function replace**At** is not ... (unless you create one or use a library that implements one) – Alex K. May 18 '17 at 11:08
  • 1
    http://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript – sumit chauhan May 18 '17 at 11:09

2 Answers2

1

Using replace():

var hello = 'Hello World!!';
    alert(hello.replace("!!",'??'));

If you want to replace all matchs in a string you can use this funct

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

Because .replace() just replace first match. Cheers

Roy Bogado
  • 4,299
  • 1
  • 15
  • 31
0

function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace("!!", "...!!");
    document.getElementById("demo").innerHTML = res;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="demo">Hello world!!</p>
<button onclick="myFunction()">Try it</button>

Check this out. Help you to get some idea.

Greetings!

Geee
  • 2,217
  • 15
  • 30