3

I want to parse the target string "Soup base vegetarian no msg " to be an array of ["Soup", "base", "vegetarian", "no msg"] so basically parse by space except when space follows the word "no" I tried below and the result wasn't exactly right:

let test = "Soup base vegetarian no msg ";
console.log(test.split(/([^no]\s)/g));

what regex should I use to achieve such?

WABBIT0111
  • 2,233
  • 2
  • 18
  • 30

3 Answers3

4

You can use this match instead of split:

var str = "Soup base vegetarian no msg ";

var arr = str.match(/(?:\bno\s+)?\S+/g);

console.log(arr);
//=> ["Soup", "base", "vegetarian", "no msg"]

Regex (?:\bno\s+)?\S+ optionally matches word no followed by 1+ whitespaces before matching 1+ non-whitespace characters.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You can use this regex ((no )?\w+).

Explanation:-

  • (no )? will either match no(no with space or nothing(?))
  • \w+ will match word(match more than one alphabet(a-z or A-Z))

var str = "Soup base vegetarian no msg";
var arr = str.match(/((no )?\w+)/g);
console.log(arr);
yajiv
  • 2,901
  • 2
  • 15
  • 25
0

A solution based on this answer using split.

The code is so weird because JS does not support negative lookbehind.

let test = "Soup base vegetarian no msg ";
var tokens = reverse(test)
  .split(/ (?!on)/g)
  .filter(x => x)
  .map(reverse);

console.log(tokens);

function reverse(s) {
  return s.split('').reverse().join('');
}
raul.vila
  • 1,984
  • 1
  • 11
  • 24