Split string by multiple delimiters and keeping some delimiters while discarding others

Viewed 41

I would like to split by the space string " " while removing it and also split by a comma "," while keeping it.

var str = "This is a word, and another."
var regexKeepCommaDelimeter = new RegExp(/(,)/,'g')
var regexKeepCommaRemoveSpace = new RegExp(/(????)/,'g')
var splitArray = str.split(regexKeepCommaRemoveSpace)
var desiredArray = ['This', 'is', 'a', 'word', ',', 'and', 'another.' ]
var testPassed = splitArray.every((x,i)=> x == desiredArray[i])
console.log('Arrays match:', testPassed)
2 Answers

One fairly simple approach would be to add spaces around any , that don't have them, then just split on space:

var splitArray = str.replace(/ ?, ?/g, " , ").split(" ");

Live Example:

var str = "This is a word, and another."
var splitArray = str.replace(/ ?, ?/g, " , ").split(" ");
console.log(splitArray);
var desiredArray = ['This', 'is', 'a', 'word', ',', 'and', 'another.' ];
console.log(splitArray.every((e, i) => e === desiredArray[i]));
.as-console-wrapper {
    max-height: 100% !important;
}

Match the space, and match and capture the comma when splitting with str.split(/\s+|(,)/).filter(Boolean).

Or, you may match any amount of chars other than whitespace and commas, or just a comma with str.match(/[^\s,]+|,/g).

var str = "This is a word, and another.";
console.log(
  str.split(/\s+|(,)/).filter(Boolean)
);
// => ["This", "is", "a", "word", ",", "and", "another."]

console.log(
  str.match(/[^\s,]+|,/g)
);
// => ["This", "is", "a", "word", ",", "and", "another."]

The .filter(Boolean) part will remove empty items from the resulting array that appear due to eventual consecutive matches, or matches at the start of the string.

Related