0

I want to create a function in javascript which accepts two arguments : a regex object and a string.
The regex can have at most one capturing group.
If there is a capturing group, it shall return $1, otherwise the remaining string;

So myfunc("hello123", /\d+/) shall return hello and
myfunc("hello123", /\w+(\d+)/) shall return 123

How to identify if there's a capturing group or not?

2
  • In your first example: myfunc("hello123", /\d+/) shall return hello ..you are replacing the second argument with nothing and returning the string. In your second example: myfunc("hello123", /\w+(\d+)/) shall return 123 you are matching and returning match[1]. There has to be a uniform behaviour to build a function on. Commented May 22, 2014 at 10:57
  • There's a logic : If there is a capturing group in the regex, it shall return $1, otherwise it shall replace the string with the given pattern. First example : myfunc("hello123", /\d+/), no matching group, so the string matching the given pattern /\d+/ shall be removed. second example myfunc("hello123", /\w+(\d+)/), there's a matching group, so I need the part that matched! Commented May 26, 2014 at 13:19

2 Answers 2

1

When using match if the pattern couldn't be matched at all null is returned. If there was a match, the string at index 0 will be the full match while subsequent indexes will contain capturing groups. Basically the first capturing group will be at index 1 and so on.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use this function:

function myfunc(str, re) {
   m = str.match(re);
   if (m && m.length == 2)
      return m[1];
   else
      return str.replace(m[0], '');
}

Testing:

myfunc("hello123", /\d+/);
hello

myfunc("hello123", /\w+?(\d+)/)
123

PS: Use m.length to figure out how many matced groups are there in the regex being passed as argument.

2 Comments

fails in this case : myfunc("hello", /\w+?(\d+)/)
It returns 123 for that case and that is your expected output also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.