Horje
JavaScript RegExp s Modifier

The ES9 of ECMAScript 2018 JavaScript has a modifier called s in regular expression (RegExp) that allows the period (.) character to match newline characters (\n), this improves pattern searches in multi-line strings by considering newlines as any other character. The use of the dot in multiline text was restrictive because it didn’t accommodate new lines until ES9, as used by modern browsers this makes handling of text blocks in regex operations easier through the s modifier.

Syntax

/regexp/s

or

new RegExp("regexp", "s")

Example 1: The given below example matches all characters inclusive of newline characters in a multiline string.

JavaScript
function example() {
    let str1 = "Hello world.\nWelcome to GeeksforGeeks.";
    let regex = /world.*Geeks/s;
    let match = str1.match(regex);
 
    console.log("Match found: " + match);
}
example();

Output
Match found: world.
Welcome to GeeksforGeeks

Example 2: The given below example shows the difference between using s modifier and not using it.

JavaScript
function example() {
    let str1 = "Hello world.\nWelcome to GeeksforGeeks.";
    
    let regexWithoutS = /world.*Geeks/;
    let matchWithoutS = str1.match(regexWithoutS);
    console.log("Without 's' modifier: " + matchWithoutS);
    
    let regexWithS = /world.*Geeks/s;
    let matchWithS = str1.match(regexWithS);
    console.log("With 's' modifier: " + matchWithS);
}
example();

Output
Without 's' modifier: null
With 's' modifier: world.
Welcome to GeeksforGeeks

Supported Browsers

The RegExp s Modifier is supported by the following browsers-

  • Google Chrome
  • Apple Safari
  • Mozilla Firefox
  • Opera
  • Microsoft Edge



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
What Do Multiple Arrow Functions Mean in JavaScript? What Do Multiple Arrow Functions Mean in JavaScript?
How to Convert a JSON String into an SQL Query? How to Convert a JSON String into an SQL Query?
How to Escape a String in JavaScript? How to Escape a String in JavaScript?
JavaScript String bold() Method JavaScript String bold() Method
JavaScript String fontsize() Method JavaScript String fontsize() Method

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16