How to replace all dots in a string using JavaScript?

There are some methods to replace the dots(.) in the string.

  • replace():
    The string.replace() function is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged.

    Syntax:



    str.replace(A, B)

    Example-1: we are replacing the dots(.) with space( ) in the text “A.Computer.science.Portal”.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html>
    <html>
      
    <head>
    </head>
      
    <body>
        <center>
            <h1 style="color:green">
              GeeksforGeeks
          </h1>
            <script>
                
                // Assigning a string 
                var str = 'A.Computer.science.Portal';
      
                // Calling replace() function 
                var res = str.replace(/\./g, ' ');
      
                // Printing original string
                document.write("String 1: " + str);
                
                // Printing replaced string
                document.write("<br>String 2: " + res);
                
            </script>
        </center>
    </body>
      
    </html>

    chevron_right

    
    

    Output:

  • Split() and Join(): We can split up strings of text with the Javascript split method and join strings using the replace characters with the join method.

    Syntax:

    string.split('.').join(' ');

    Example-2: we are replacing the dots(.) with space( ) using split and join.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html>
    <html>
       <head>
       </head>
       <body>
           <center>
          <h1 style="color:green">GeeksforGeeks</h1>
          <script>
               
              // Assigning a string 
              let str = 'A.Computer.Science.portal';
                
              // Calling split(), join() function 
              let newStr = str.split('.').join(' ');
                
              // Printing original string
             document.write("String 1: "+str);
               
             // Printing replaced string
             document.write("<br>String 2: "+newStr);
          </script>
          </center>
       </body>
    </html>

    chevron_right

    
    

    Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.