hello. I want to change the sentence order randomly (by dot). For example:
1 My mother is home. 2 My father is at work. 3 My sister loves hot milk. 4 My lovely dog is here. 5 I go to mall. 6 She seen Jupiter. 7 I read a book. 8 I drove all night. 9 Book is here. 10 Many people want.
The output should be:
8 I drove all night. 5 I go to mall. 1 My mother is home. 7 I read a book. 2 My father is at work. 9 Book is here. 3 My sister loves hot milk. 10 Many people want. 4 My lovely dog is here. 6 She seen Jupiter.
Regex doesn’t really deal well with randomness – it won’t be random in this case because you’d need to specify the replace pattern every time.
match will give you an array of the sentences, you can shuffle and then rejoin that:
const input = "1 My mother is home. 2 My father is at work. 3 My sister loves hot milk. 4 My lovely dog is here. 5 I go to mall. 6 She seen Jupiter. 7 I read a book. 8 I drove all night. 9 Book is here. 10 Many people want.";
input.match(/\d+ .+?\./g);
Gives you
[ '1 My mother is home.',
'2 My father is at work.',
'3 My sister loves hot milk.',
'4 My lovely dog is here.',
'5 I go to mall.',
'6 She seen Jupiter.',
'7 I read a book.',
'8 I drove all night.',
'9 Book is here.',
'10 Many people want.' ]
[ 'My mother is home.',
' My father is at work.',
' My sister loves hot milk.',
' My lovely dog is here.',
' I go to mall.',
' She seen Jupiter.',
' I read a book.',
' I drove all night.',
' Book is here.',
' Many people want.' ]
Or maybe
input.replace(/\.\s/g, ".#").split("#")
So replacing every gap between sentences with a character that doesn’t appear in the sentences, which you can then split on, which gives
[ 'My mother is home.',
'My father is at work.',
'My sister loves hot milk.',
'My lovely dog is here.',
'I go to mall.',
'She seen Jupiter.',
'I read a book.',
'I drove all night.',
'Book is here.',
'Many people want.' ]
I don’t think you’re really taking any notice here, either of what I’m writing or what the answers are saying.
What do you want this for, and what language are you using?
You need to split the text into sentences, store those in a data structure you can shuffle, then shuffle it. Regex allows you to define the string pattern for a sentence, but it doesn’t give you the second part.
It’s as simple as using .split smartly. The answer you found doesn’t work because it doesn’t address randomization which is something a RegExp engine C A N N O T - D O.
str.split(/\.\s+/).join('. ')
This code does not do what you intended because it only splits and rejoins the array of sentences with a dot and a space. You need an intermediate step: shuffling the array in random order.
Javascript does not provide that out of the box, it just gives you Math.random() which can be used as a base. You could copy-paste some code from stack overflow:
Make it an array prototype method that returns the array and then you can do: