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.
1 Answer
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.
5 Comments
Beardy
This could also be shortened to
var stateCode = /\([A-Z]{2}\)/.exec(input)[1];Daniel Calliess
And there's more than one good tool out there that let's you immediately test what you are doing.
Martin Ender
@Beardy yes, but for beginner questions I prefer the unoptimized versions that tell a bit more about the workings of the code.
cbayram
@m.buettner, good answer, given the question you should match the "SD" and not "(SD)" though
Martin Ender
@cbayram sorry I forgot the capturing parentheses when copying the code from Chrome's developer tools ;).
(<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? .../(SD)/,/(sD)/i,/\((SD)\)/,/(SD)\)$/,/^.+\((SD)\)$/will all match your situation but what is best? This is what I mean./\(([A-Z]{2})\)/i