AngeloC
AngeloC

Reputation: 3523

how to extract two characters from a string in javascript

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}\)$/))

Upvotes: 1

Views: 51

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626851

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);

Upvotes: 1

Related Questions