javascript - Split a string but keep the Comma


Keywords:javascript 


Question: 

I need to split a sentence string that keeps the non-whitespace such as . or ,. I need them to be included within the array string being split. Not in their own seperate array index.

const regex = /\W(?:\s)/g

function splitString (string) {
  return string.split(regex)
}

console.log(splitString("string one, string two, thing three, string four."))

// Output ["string one", "string two", "thing three", "string four."]
// Desired ["string one,", "string two,", "string three,", "string four."]

1 Answer: 

Perhaps using a match approach instead of a split approach:

"string one, string two, thing three, four four.".match(/\w+(?:\s\w+)*\W?/g);
// [ 'string one,', 'string two,', 'thing three,', 'four four.' ]

or something more specific (this way you can easily choose one or several delimiter characters):

"string one, string two, thing three, four four.".match(/\S.*?(?![^,]),?/g);