Languages
[Edit]
EN

JavaScript - \R equivalent in RegEx

10 points
Created by:
Hayley-Mooney
377

In this short article, we would like to show how to use \R character class regular expressions in JavaScript what is not available by default.

Quick solution: use \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029] as equivalent to \R.

 

Practical example:

// ONLINE-RUNNER:browser;

var LINE_EXPRESSION = /\u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]/g; // expression symbols order is very important

var text = 'line 1\n' +
    'line 2\r' +
    'line 3\r\n' +
    'line 4\n\r' +
    'line 5';

var lines = text.split(LINE_EXPRESSION);

console.log(lines);

Warning: above expression will treat \n\r as two new lines symbols! - it is very rare case (used on: Acorn BBC and RISC OS spooled text output) 

 

Where:

UnicodeDescription
\u000D\000A\r\n pair
\u000ALine Feed / LF  (\n)
\u000BLine Tabulation
\u000CForm Feed (\f)
\u000DCarriage Return / CR (\r)
\u0085Next Line (NEL)
\u2028Line Separator
\u2029Paragraph Separator

Source

  1. https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html (Linebreak matcher section)

See also

  1. JavaScript - split string by new line character

  2. JavaScript - universal new lines splitting symbol example

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join