Split string into sentences in javascript

后端 未结 8 1170
悲哀的现实
悲哀的现实 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条回答
  •  Happy的楠姐
    2020-11-29 06:39

    You're safer using lookahead to make sure what follows after the dot is not a digit.

    var str ="This is a long string with some numbers [125.000,55 and 140.000] and an end. This is another sentence."
    
    var sentences = str.replace(/\.(?!\d)/g,'.|');
    console.log(sentences);
    

    If you want to be even safer you could check if what is behind is a digit as well, but since JS doesn't support lookbehind, you need to capture the previous character and use it in the replace string.

    var str ="This is another sentence.1 is a good number"
    
    var sentences = str.replace(/\.(?!\d)|([^\d])\.(?=\d)/g,'$1.|');
    console.log(sentences);
    

    An even simpler solution is to escape the dots inside numbers (replace them with $$$$ for example), do the split and afterwards unescape the dots.

提交回复
热议问题