How to skip character in capture group in JavaScript Regexp?

You cannot skip a character in a capture group. A match is always consecutive, even when it contains things like zero-width assertions. However, you can use techniques to extract specific parts while ignoring unwanted characters.

Understanding the Problem

When you need to match a pattern but only capture certain parts, you can use non-capturing groups (?:...) and capturing groups (...) strategically to ignore unwanted characters.

Example: Extracting Username After Prefix

The following example shows how to match a string with a prefix but only capture the username part:

<html>
   <head>
      <script>
         var str = "Username akdg_amit";
         var myReg = /(?:^|\s)akdg_(.*?)(?:\s|$)/g;
         
         var res = myReg.exec(str);
         document.write("Extracted username: " + res[1]);
      </script>
   </head>
   
   <body>
   </body>
</html>

Output

Extracted username: amit

Breaking Down the Pattern

The regular expression /(?:^|\s)akdg_(.*?)(?:\s|$)/g works as follows:

  • (?:^|\s) - Non-capturing group matching start of string or whitespace
  • akdg_ - Literal text to match but not capture
  • (.*?) - Capturing group for the username (non-greedy)
  • (?:\s|$) - Non-capturing group matching whitespace or end of string

Alternative Approach with Multiple Capture Groups

<html>
   <head>
      <script>
         var email = "user@example.com";
         var emailReg = /([^@]+)@([^.]+)\.(.+)/;
         
         var match = emailReg.exec(email);
         if (match) {
            document.write("Username: " + match[1] + "<br>");
            document.write("Domain: " + match[2] + "<br>");
            document.write("Extension: " + match[3]);
         }
      </script>
   </head>
   
   <body>
   </body>
</html>

Output

Username: user
Domain: example
Extension: com

Key Points

  • Use non-capturing groups (?:...) for parts you want to match but not capture
  • Use capturing groups (...) only for parts you want to extract
  • Access captured groups using result[1], result[2], etc.
  • The full match is always available at result[0]

Conclusion

While you cannot skip characters within a capture group, you can strategically use non-capturing groups to match unwanted parts and capturing groups to extract only the data you need. This approach gives you precise control over what gets captured from your regex matches.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements