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.?

6
  • 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). Commented Feb 23, 2012 at 19:23
  • why there is empty string at the beginning of string? Commented Feb 23, 2012 at 19:25
  • 3
    Because "Visit Microsoft!" === "" + "Visit Microsoft!" Commented Feb 23, 2012 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"). Commented Feb 23, 2012 at 19:26
  • 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-!-" Commented Feb 23, 2012 at 19:29

1 Answer 1

2

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.