E
E
Eugene2020-04-19 01:24:21
JavaScript
Eugene, 2020-04-19 01:24:21

How to extract a substring in js using a regular expression?

Good afternoon.
There is a line:

"Organix (dry food) for small breed dogs, with chicken, Adult Dog Small Breed Chicken (12 kg)"


From it it is necessary to receive two lines.
First line.
The first line must meet the following conditions:
  • The string is contained in brackets "(" and ")"
  • The string contains numbers

At the output, we should get the following line:

"12 kg"


Second line.
The second line must meet the following condition:
It must not contain a parenthesized string (including parentheses) that contains numbers.
At the output, we should get the following line:

"Organix (dry food) for small breed dogs, with chicken, Adult Dog Small Breed Chicken"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-04-19
@prukon

function getStrings(str) {
  const str1 = str.match(/\(.+?\)/g)?.find(n => /\d/.test(n)) || '';
  return {
    str1: str1.slice(1, -1),
    str2: str.replace(str1, ''),
  };
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question