0

how can I split a string and take the separator into the array? For example I have a string with two sentences:

"I am learning Javascript. The most exiting programming language."

I would like to have following result after splitting with split(".") :

array[0] consists of "I am learning Javascript. 
array[1] consists of "The most exiting programming language."

I don't want to lose the punctuation at the end of a sentence. How can I achieve that?

Update: This is not the same issue like here: Javascript and regex: split string and keep the separator

because the br-tag is not displayed, since it is html code. The punctuation in my case should be seen explicitly.

Martin
  • 33
  • 4

3 Answers3

0

Instead of splitting the string, you can match a sequence of non dots that terminates with a dot (regex101):

const str = "I am learning Javascript. The most exiting programming language."

const result = str.match(/[^.]+\./g)

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

You could use match instead and look for any character followed by a dot an whitespace.

var string = "I am learning Javascript. The most exiting programming language.";

console.log(string.match(/.*?\.\s*/g));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Use the following code to achieve what you seek.

 let sentence = "I am learning Javascript. The most exiting programming language."

const splitedArray = sentence.split(".");

let i=0;

for(i;i<splitedArray.length-1;i++){
 console.log(`array[${i}] consists of `+splitedArray[i]+`.`); 
}

This will work for all such sentences ending with the dot(.). This is a quick dynamic solution to your problem. Hope this helps.

https://codepen.io/anon/pen/Pgyovp?editors=1112

Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35