Home > Blockchain >  Javascript Regex to get list of any words except a specific word but also get that specific word in
Javascript Regex to get list of any words except a specific word but also get that specific word in

Time:05-30

I want to get all categories listed in example below fruit and meat but not word mandatory but I want to still get mandatory if present :

categories fruit meat mandatory

I tried to inspire from Match everything except for specified strings

https://regex101.com/r/peXJXx/1

/(categories )(^(?!. (mandatory)))(mandatory)?/gis

But can't get it work

CodePudding user response:

If you insist on using regex, this might be what you want.

const input = "categories fruit meat mandatory";
const regex = /\w /gm;
const regex2 = /^\w /g;

const results = input.matchAll(regex);

let type = input.match(regex2)[0];

let isMandatory = false;
let isCategory = false;
let categories = [];
for (const result of results){
    switch(result[0]){
    case "categories": isCategory = true; break;
    case "mandatory": isMandatory = true; break;
    default: categories.push(result[0]);
  }
}
console.log("Type: "   type);
console.log("Categories: "   categories.join(", "));
console.log("Mandatory: "   (isMandatory ? "Yes" : "No"));
Type: categories
Categories: fruit, meat
Mandatory: Yes

You can spruce it up however you want. Essentially if you have multiple inputs, you'd loop over each string and run this code. If you have other types instead of category, you can add something like isDepartment = false and then in the switch do case "departments": isDepartment = true; break;.

You could also just modify the regex to ignore the first word and create a second regex pattern to identify what the first word is specifically like const regex2 = /^\w /g; and then do let type = input.match(regex2)[0];.

Here's a live sample https://jsfiddle.net/gey3oqLp/1/

Edit: Actually now that I think about it. If we're going the switch route, we don't need to match anything specific in the regex. We only need to match each word and deal with it later down the road. I've removed updated the regex to the simpler version.

CodePudding user response:

const r = 'categories fruit meat mandatory';
const [, ...categories] = r.split(' ').filter(_ => _ !== 'mandatory');

You don't need Regex for such a problem, I used split(' ') to split the string into words (convert it to an array), then filter them from 'mandatory', I used also destructuring to remove the first element.

  • Related