writofmandamus
writofmandamus

Reputation: 1241

How to capture group in Javascript Regex?

I am trying to capture customer.name from hello @customer.name from the end of the text string.

However, I can't seem to get the @ character out of it. It gives @customer.name.

Right now my regex expression is:

@([0-9a-zA-Z.]+)$

Upvotes: 2

Views: 1233

Answers (2)

JasonB
JasonB

Reputation: 6368

Your regex works fine, here's some code to use it to access your capture group using the regex .exec function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

let testString ='hello @customer.name',
    pattern = /@([0-9a-zA-Z.]+)$/,
    match = pattern.exec(testString);
    
console.log(match[1]); // abc

Upvotes: 2

CRice
CRice

Reputation: 32226

Use the .match method of the string. The result will be null if there was no match with the given regex, otherwise it will be an array where:

  • The first element is the entire matched string, @customer.name in your case
  • The remaining elements are each capture group. You have one capture group so that would end up in the 1st index. In your case this will be customer.name, the string you want.

See this snippet. Your regex already looks correct, you just need to pull only the capture group from it instead of the entire matched string.

const str = "hello @customer.name"
const reg = /@([0-9a-zA-Z.]+)$/;

const match = str.match(reg)
console.log(match)
console.log("Matched string:", match[0]);
console.log("First capture group:", match[1]);

Upvotes: 3

Related Questions