Search This Blog

2024/03/23

Javascript Regular Expression:Split a para into array of its sentences

Here is my paragrapgh.

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.

I want to get an array containing each sentence of this paragrapgh.

Code:
let bunchOfSentences='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 =/[^\.]+/g
var lines = bunchOfSentences.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'
]

Note :
if we changed the regular expression pattern in above code to below

var pattern =/[^\.\s]+/g

then we get array containing all words in paragrapgh.

Here is Output of same code with change in pattern values.

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'
]

No comments:

Post a Comment