As pointed out by others, there is no greedy flag for your regular expression. The correct expression should be something like what others have given you.
var r = "I\nam\nhere"; var s = r.replace(/\n/g,' ');
I would like to point out the difference from what was happening from the very beginning. you used the following statements
var r = "I\nam\nhere"; var s = r.replace("\n"," ");
The statements are indeed valid and replace one instance of the \ n character. It uses a different algorithm. When providing a replacement string, it will look for the first occurrence and simply replace it with the string specified as the second argument. When using regular expressions, we are not just looking for a suitable character, we can write complex matching syntax, and if a match is found or several, it will be replaced. More information on regular expressions for JavaScript can be found here at w3schools .
For example, the method you made may be more general for analyzing input from several different types of files. Due to differences in the operating system, files with \ n or \ r, where a new line is required, are quite common. To be able to process both codes, you can rewrite it using some of the regular expression functions.
var r = "I\ram\nhere"; var s = r.replace(/[\n\r]/g,' ');
Pablo jomer
source share