I want to extract characters in parentheses and return empty characters if the result is empty.

Asked 1 years ago, Updated 1 years ago, 317 views

Find the range bounded by () from the string passed by the argument str and return the string for that part.

  • () returns empty characters if the contents are empty.
  • () returns the contents of the first parenthesis found if there are multiple
  • ()(Quickest match)
  • Returns null if
  • () is not found.

If () is empty, I want to return an empty character, but it says null.
Could you please let me know?

function extractStr(str){
  varret=/\(.+?)\)/.exec(str);
  return ret?ret[1]: null;
}

javascript regular-expression

2022-11-06 08:48

1 Answers

If the contents of ( ) are empty, I want to return empty characters, but it says null.

The regular expression is \(.+?)\), and (.+?) is specified in parentheses. +? is one or more characters long, so if () is empty, does not apply and fails.The regular expression must be \(.*?)\) using *? for zero or more characters if you want it to succeed even if it is empty.


2022-11-07 08:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.