Replace '\' n in javascript

I am trying to replace in JavaScript using:

r = "I\nam\nhere"; s = r.replace("\n"," "); 

But instead of giving me

I'm here

as the value of s , He returns the same.

Where is the problem?

+7
source share
5 answers

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,' '); 
+8
source

The problem is that you need to use the g flag to replace all matches, since by default replace() only works on the first match found:

 var r = "I\nam\nhere", s = r.replace(/\n/g,' '); 

To use the g flag, you will need to use a regex approach.

By the way, when declaring variables, use var , otherwise the variables you created are global, which can lead to problems later.

+10
source

use s = r.replace(/\\n/g," ");

Get link :

The "g" in the javascript replacement code means "greedy", which means that the replacement should happen more than once, if possible

+3
source

.replace() requires a global match flag:

 s = r.replace(/\n/g, " "); 
+2
source

You can use:

 var s = r.replace(/\n/g,' ').replace(/\r/g,' '); 

since different SOs use different ways to set a "new line", for example: Mac Unix Windows, after that you can use another function to normalize the spaces.

0
source

All Articles