Replace() method, the string for a specified value is searched for a regular expression and a new string is returned where the specific values are replaced.
Replace() cites two arguments:
Replace() where multiple spaces are shown to be removed with a single space:
The developers need to keep one thing in mind that while printing the strings on the web page, the difference will not be visible. The browsers treat multiple spaces as a single space until the developers preserve the white space.
In the above example, the new string is returned that provides the Output of single space. Here, to perform the global search and
replace() method, the ‘g’ switch can be included in a regular expression. However, in case, the first parameter here is a string as shown above then developers must include ‘g’ switch in the flags parameter.
Moreover, here in the example of replacing multiple spaces into single space, the string method is used. The
Replace() searches for the match between a string and a regular expression that acts as a tool and the output is given as a new string. In the above Output, this function has helped to remove leading spaces that removed multiple spaces and merged into a single space.
Replace() function helps in unifying the spaces and reduces a number of white spaces that occurs while writing the script. For replacing all the occurrences of multiple spaces, the use of ‘g’ or a global modifier in the string method should be used.