4

I need to split a string by \.\s but leave the . appended to the array element.

Taking this string as a test, Lorem Ipusm. Excepteur sint occaecat. I need the output array to be:

[0] => Lorem Ipsum.
[1] => Excepteur sint occaecat.

See how the . still remains intact?

I believe I need a lookbehind regex because /\.(?=\s)*/ doesn't work, instead the . ends up at the beginning of each sentence after it.

James
  • 5,137
  • 5
  • 40
  • 80
  • Are you looking for this? http://stackoverflow.com/questions/4514144/js-string-split-without-removing-the-delimiters – AlessandroEmm Apr 29 '13 at 12:43
  • Yeah I did, but I got an invalid capture group, or something? – James Apr 29 '13 at 12:43
  • possible duplicate of [Javascript and regex: split string and keep the separator](http://stackoverflow.com/questions/12001953/javascript-and-regex-split-string-and-keep-the-separator) – mplungjan Apr 29 '13 at 12:44
  • @TillHelge, JavaScript does not support Lookbehind assertions. – stema Apr 29 '13 at 12:53
  • @stema Yeah...I just messed around with a jsfiddle and realized that by now. Never needed that before. Thanks for confiming my suspicion. ;) – Till Helge Apr 29 '13 at 13:17

1 Answers1

4

try this:

var s = "Lorem Ipsum. Excepteur sint occaecat.",
    parts = s.match(/(.+?\.(?:\s|$))/g); 
    // ["Lorem Ipsum. ", "Excepteur sint occaecat."]
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • Note the space at the end of the first result in array - but it is easy to take care of, though. – nhahtdh Apr 29 '13 at 12:45