Split string into sentences in javascript

后端 未结 8 1075
悲哀的现实
悲哀的现实 2020-11-29 06:08

Currently i am working on an application that splits a long column into short ones. For that i split the entire text into words, but at the moment my regex splits numbers to

8条回答
  •  有刺的猬
    2020-11-29 06:42

    @Roger Poon and @Antonín Slejška 's answers work good.

    It'd better if we add trim function and filter empty string:

    const splitBySentence = (str) => {
      return str.replace(/([.?!])(\s)*(?=[A-Z])/g, "$1|")
        .split("|")
        .filter(sentence => !!sentence)
        .map(sentence => sentence.trim());
    }
    

    const splitBySentence = (str) => {
      return str.replace(/([.?!])(\s)*(?=[A-Z])/g, "$1|").split("|").filter(sentence => !!sentence).map(sentence => sentence.trim());
    }
    
    const content = `
    The Times has identified the following reporting anomalies or methodology changes in the data for New York:
    
    May 6: New York State added many deaths from unspecified days after reconciling data from nursing homes and other care facilities.
    
    June 30: New York City released deaths from earlier periods but did not specify when they were from.
    
    Aug. 6: Our database changed to record deaths by New York City residents instead of deaths that took place in New York City.
    
    Aug. 20: New York City removed four previously reported deaths after reviewing records. The state reported four new deaths in other counties.(extracted from NY Times)
    `;
    
    console.log(splitBySentence(content));

提交回复
热议问题