Javascript - .split with Regex to Return All Matches If Next Character Is Not

Viewed 198

Using .split() with Regex, what is the proper way to perform a split with using whitespace with multiple characters?

For example, with a string like:

const str = 'Supreme > 22 < 27 < 34> 185';

the expected outcome would be:

const output = ['Supreme', '> 22', '< 27', '< 34', '> 185'];

I have attempted using .split() with the pattern /.+?(?=>|<)/, but it returns the opposite like:

const opposite = [ '', '', '', '', '> 185' ]

2 Answers

You can use

/\s*(?=[><])/

See the regex demo. It matches:

  • \s* - zero or more whitespace chars
  • (?=[><]) - immediately followed with < or >.

Since the pattern can match empty strings, there will be empty items in the resulting array, that will need removing, e.g. with .filter(Boolean).

See the JavaScript demo:

const str = 'Supreme > 22 < 27 < 34> 185';
console.log(str.split(/\s*(?=[><])/).filter(Boolean));

A matching approach can be implemented using

console.log('Supreme > 22 < 27 < 34> 185'
   .match(/(?:^|[<>])[\s\S]*?[^\s<>](?=\s*[<>]|$)/g))

See the regex demo. Details:

  • (?:^|[<>]) - start of string or < or >
  • [\s\S]*? - any zero or more chars, as few as possible
  • [^\s<>] - any char but a whitespace, > and <
  • (?=\s*[<>]|$) - immediately followed with any 0+ whitespace chars and then < or > or end of string.

You can use match method. It will return your expected output.

const str = 'Supreme > 22 < 27 < 34> 185';
const ret = str.match(/(\w+)|(<\s*\d+)|(>\s*\d+)/g);
console.log(ret);

Related