Search This Blog

2024/03/23

Javascript Regular Expression: Multiline matching

The multiline flag (m) causes ^ and $ to match the beginning and end of a line,

In addition to the beginning and end of a string. You could use this flag to
parse text such as the following,

Code:
//quoting in backtick - the most simple way
let multiLineStringTwo=`India is my country.
All indians are my brother & sister.
I love my country and I am proud of its rich and varied heritage.
I shall always strive to be worthy of it.
I shall give my parents, teachers and all elders respect and treat everyone with courtesy.`;

var pattern =/^.*$/gm
var lines = multiLineStringTwo.match(pattern)
console.log(lines)

Output:
[
'India is my country.',
'All indians are my brother & sister.',
'I love my country and I am proud of its rich and varied heritage.',
'I shall always strive to be worthy of it. ',
'I shall give my parents, teachers and all elders respect and treat everyone with courtesy.'
]
Explanation:
Here we use string method match() to break the text into individual
lines and place them in the array lines.

No comments:

Post a Comment