0

I want to extract this "SD" from text "SouthDacota (SD)" in Javascript. I am newbie to regex in js and wanted to know if any one has any ideas.

7
  • @8GB, Do go through some regex tutorials. Big part of utilizing regular expressions is to understand your data range as well as what you want to accomplish. Will (<letter><letter>) always be your format? Will it always be at the end of the string? Will it be 2 and only 2 letters? Or are you simply matching the letters SD inside of paranthesis? ... Commented Nov 7, 2012 at 21:13
  • /(SD)/, /(sD)/i, /\((SD)\)/, /(SD)\)$/, /^.+\((SD)\)$/ will all match your situation but what is best? This is what I mean. Commented Nov 7, 2012 at 21:19
  • @ Ben Swinburne I used this "((\w{2})?)" donest help though. @cbayram basically the text can change what I need is to extract whats inside of "()". Commented Nov 7, 2012 at 21:22
  • @8GB Then what m.buettner gave you should suffice. Only changes I'd make is to make it case-insensitive and not make the parentheses part of the match. /\(([A-Z]{2})\)/i Commented Nov 7, 2012 at 21:26
  • @cbayram and m.buettner Thanks. Commented Nov 7, 2012 at 21:29

1 Answer 1

2

The simplest regex would match the parentheses, and in between two upper-case letters. In addition you can "capture" the two letters (with unescaped parentheses), so you can retrieve them without the parentheses:

var regex = /\(([A-Z]{2})\)/;
var matches = inputString.match(regex);
var stateCode = matches[1];

But you should really read up on some basics.

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

5 Comments

This could also be shortened to var stateCode = /\([A-Z]{2}\)/.exec(input)[1];
And there's more than one good tool out there that let's you immediately test what you are doing.
@Beardy yes, but for beginner questions I prefer the unoptimized versions that tell a bit more about the workings of the code.
@m.buettner, good answer, given the question you should match the "SD" and not "(SD)" though
@cbayram sorry I forgot the capturing parentheses when copying the code from Chrome's developer tools ;).

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.