Search code examples
javascriptphpstringwhitespacestring-concatenation

In JavaScript, if multiple spaces are added between two strings why they get converted to a single space during code execution?


While learning JavaScript I come across one issue. When I add multiple spaces between two strings, all spaces get converted to a single space. I tried to add multiple spaces between two strings with the help of concatenation operator(+). Also, I tried by adding multiple white spaces after the first string and before the second string but every time I get the same result. Two strings are separated by only one space in between them.

I searched for the cause but everyone is telling how to overcome this problem with the help of some regular expression and string replace function in JavaScript. I want the root cause of this problem.

I also know PHP. In PHP, this thing doesn't happen, PHP strings behave as expected by the developer. Whatever number of spaces I add in between, before or after the string they get added then why not in JavaScript?

Someone please explain me the cause and difference in this case between PHP and JavaScript.

I tried following expressions :

"John" + "               "  + "Doe";

"John          " + "         "  + "      Doe";

"John" + "       "  + "          Doe";

"John                Doe";

The output I got every time is : John Doe


Solution

  • The reason is not JavaScript, but HTML. The standard says that any number of whitespaces (spaces, linebreaks, etc ...) get reduced to a single space.

    If you want to prevent this behavior, use  .