2

See my code

<html>
<body>

<script type="text/javascript">

var str="Visit Microsoft!";

document.write( str = str.replace("",'ss'));

</script>
</body>
</html>

The output is

 ssVisit Microsoft!

Why is it happening.?

Jinu Joseph Daniel
  • 5,864
  • 15
  • 60
  • 90
  • 7
    `replace` with a string will only replace the first occurrence of that string. You pass an empty string, which is found at the beginning of the string (`"something".indexOf("")` returns `0`). – Felix Kling Feb 23 '12 at 19:23
  • why there is empty string at the beginning of string? – Jinu Joseph Daniel Feb 23 '12 at 19:25
  • 3
    Because `"Visit Microsoft!" === "" + "Visit Microsoft!"` – Alex K. Feb 23 '12 at 19:26
  • Between the beginning of the string and the first character, there is *nothing*. Same goes for anything between characters. The empty string can be found between any characters (you can do the same what Alex did, e.g. `"foo" + "" + "bar" === "foobar"`). – Felix Kling Feb 23 '12 at 19:26
  • and at the end character just try indexof("") and lastIndexof("") but what are you trying to achieve ? – VirtualTroll Feb 23 '12 at 19:28
  • 2
    To further illustrate, here's what happens, if you replace _all_ empty/zero-length strings in `str`: `str.replace(new RegExp("", "g"), "-")` → `"-V-i-s-i-t- -M-i-c-r-o-s-o-f-t-!-"` – Flambino Feb 23 '12 at 19:29

1 Answers1

2

This is correct because every string begins with an empty string. See below post for more info:

Why does "abcd".StartsWith("") return true?

Community
  • 1
  • 1
Pramod
  • 36
  • 4