The ‘s’ Flag


The 's' flag is useful when the target string contains new lines. Without the 's' flag, the '.' operator matches all characters except the new line. With the 's' flag, the '.' operator matches all characters including the new line. In the below code, a match is found for the pattern with the ‘s’ flag because the new line (\n) is matched by the character class ‘.’. But when the ‘s’ flag is removed, the same input string fails, because the ‘\n’ is not matched by the dot ‘.’ character class.

let wordPttn = /bn.*an/s;
let targetString = "bngyt6568\nghhghan";
let result = targetString.match(wordPttn);
console.log((result !== null ?
`Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'`
: `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));
console.log("---------------------------------------------");
wordPttn = /bn.*an/;
result = targetString.match(wordPttn);
console.log((result !== null ?
`Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'`
: `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));

Output:

Pattern /bn.*an/s FOUND in 'bngyt6568
ghhghan'. Matched string is 'bngyt6568
ghhghan'
---------------------------------------------
Pattern /bn.*an/ NOT FOUND in 'bngyt6568
ghhghan'