Tutorial :difference between \r and \n



Question:

what is the difference between \r and \n in regular expression.
Can someone explain to me with an example ?


Solution:1

\r is "Carriage Return" (CR, ASCII character 13), \n is "Line Feed" (LF, ASCII character 10). Back in the days, you had two ASCII characters at the end of each line to tell a printer what to do - CR would tell the printer to go back to the left edge of the paper, LF would advance to the next line.

Operating systems still have different conventions as to what the end of a line looks like -- some of them have \n\r, some have \n, some have \r\n.

In Javascript, you mostly deal with \n - this is how strings are typically switching to the next line. However, depending on what strings you are working with, you may be encountering \r as well. What exactly are you doing?


Solution:2

Normally \r represents a carriage return character (ASCII 0x0d), and \n is a newline character (ASCII 0x0a). This page has a list of all the special characters, quoted here for completeness:

  • \f matches form-feed.
  • \r matches carriage return.
  • \n matches linefeed.
  • \t matches horizontal tab.
  • \v matches vertical tab.
  • \0 matches NUL character.
  • [\b] matches backspace.
  • \s matches whitespace (short for [\f\n\r\t\v\u00A0\u2028\u2029]).
  • \S matches anything but a whitespace (short for [^\f\n\r\t\v\u00A0\u2028\u2029]).
  • \w matches any alphanumerical character (word characters) including underscore (short for [a-zA-Z0-9_]).
  • \W matches any non-word characters (short for [^a-zA-Z0-9_]).
  • \d matches any digit (short for [0-9]).
  • \D matches any non-digit (short for [^0-9]).
  • \b matches a word boundary (the position between a word and a space).
  • \B matches a non-word boundary (short for [^\b]).
  • \cX matches a control character. E.g: \cm matches control-M.
  • \xhh matches the character with two characters of hexadecimal code hh.
  • \uhhhh matches the Unicode character with four characters of hexadecimal code hhhh.


Solution:3

\n is linefeed

\r is carriage return

In windows, for example, line endings are \r\n. In the vast majority of other operating systems, they are \n.


Solution:4

\r and \n are digital representations of the way you would advance to the next line on a typewriter. \r is a carriage return and \n is a newline (also known as a linefeed). On a typewriter, to go to the start of the new line, you would return the carriage to the leftmost position and then feed the paper up a line.

Unix uses \n to mean new line, Macs prior to OS9 used \r, and Windows uses \r\n.


Solution:5

\n --> For a new line

\r --> For carriage return


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »