Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

328
Views
Regex JS- group default value / create an empty group if value not found

I have the following string:

"Group: I_am_group |SubGroup: I_am_subgroup"

And the following regex:

Group:\s(?<group>\w+) \|SubGroup:\s(?<subGroup>\w*)

The result is:

result

Until here- it's perfect to me, but when I am having the following case:

for the following strings:

1. "Group: I_am_group |SubGroup:"
2. "Group: I_am_group |"
3. "Group: I_am_group"

I want to get the result (e.g. for the string "Group: I_am_group"):

Match1      Group: I_am_group
group       I_am_group
subGroup    null

Is it possible with regex to create an empty group when it's not found? or give a default value to a group if the value not found?

In this case, I want to create the group named- 'subGroup' on the result with the value- null.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Unmatched groups per spec have value undefined, not null. A named group is unmatched, for example, when it appears inside another optional group that is unmatched.

Now take your three example strings that should produce an empty group and compare them with the original string "Group: I_am_group |SubGroup: I_am_subgroup".

  • In string (1.), " I_am_subgroup" is missing. That's \s(?<subGroup>\w*) in the regular expression.
  • In string (2.), "SubGroup: I_am_subgroup" is missing. That's SubGroup:\s(?<subGroup>\w*) in the regular expression.
  • In string (3.), " |SubGroup: I_am_subgroup" is missing. That's \|SubGroup:\s(?<subGroup>\w*) in the regular expression.

By enclosing all three of these parts in an optional group, we get

/Group:\s(?<group>\w+)( \|(SubGroup:(\s(?<subGroup>\w*))?)?)?/

This is a regular expression that matches in all cases with an empty match for subGroup. Note though that \w* can be replaced with \w+, unless you would like subGroup to be an empty string (not undefined) in cases when all other parts are present.

const regExp = /Group:\s(?<group>\w+)( \|(SubGroup:(\s(?<subGroup>\w+))?)?)?/;

const str1 = "Group: I_am_group |SubGroup:";
const str2 = "Group: I_am_group |";
const str3 = "Group: I_am_group";

console.log(str1.match(regExp).groups);
console.log(str2.match(regExp).groups);
console.log(str3.match(regExp).groups);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!