1

I tried to extract 'US' from the following string, but it returns null, any idea? Thanks

console.log('sample sample 1234 (US)'.match(/\(W{2}\)$/))
1
  • It should be \w{2} or better [A-Z]{2} Commented Nov 4, 2016 at 9:42

1 Answer 1

1

W matches a letter W. It should be \w{2} or better [A-Z]{2}. Capture it with (...) and access the 1st captured value:

console.log('sample sample 1234 (US)'.match(/\(([A-Z]{2})\)$/)[1]);
// Or, with error checking
let m = 'sample sample 1234 (US)'.match(/\(([A-Z]{2})\)$/);
let res = m ? m[1] : "";
console.log(res)

If you do not want to access the contents of the capturing group, you need to post-process the results of /\([A-Z]{2}\)$/ regex:

let m = 'sample sample 1234 (US)'.match(/\([A-Z]{2}\)$/);
let res = m[0].substring(1, m[0].length-1) || "";
console.log(res);

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

4 Comments

thanks, two approaches all works, it returns '(US)', if I want only the 'US'?
What do you mean by "it returns (US)"? See the console output. I added a third approach, please be specific.
i meant if I can get only 'US' without parentheses
All my "3" (actually, 2) approaches get you the US without parentheses. Show all relevant code to see if you have other issues there.

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.