cclloyd
cclloyd

Reputation: 9195

Split string by whitespace, keeping escaped characters

I'm trying to split a string by its whitespace, but keep any escaped whitespace characters.

Example line:

/etc/space\ in\ folder\ name/files  /mnt/files  none    defaults    0   0

I want to split that up by the whitespace (tab or spaces) yet keep the escaped whitespace characters (\ ) as one item.

So in this case it would split it into 6 items.

How can I achieve this?

Upvotes: 0

Views: 43

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

A regular expression can match any escaped character, or any character that isn't a space:

const str = String.raw`/etc/space\ in\ folder\ name/files  /mnt/files  none    defaults    0   0`;
console.log(
  str.match(/(?:\\.|\S)+/g)
);

Upvotes: 1

Related Questions