Kendrid360
Kendrid360

Reputation: 3

javascript regex to extract the first character after the last specified character

I am trying to extract the first character after the last underscore in a string with an unknown number of '_' in the string but in my case there will always be one, because I added it in another step of the process.

What I tried is this. I also tried the regex by itself to extract from the name, but my result was empty.

var s = "XXXX-XXXX_XX_DigitalF.pdf"

var string = match(/[^_]*$/)[1]

string.charAt(0) 

So the final desired result is 'D'. If the RegEx can only get me what is behind the last '_' that is fine because I know I can use the charAt like currently shown. However, if the regex can do the whole thing, even better.

Upvotes: 0

Views: 1768

Answers (1)

nnnnnn
nnnnnn

Reputation: 150010

If you know there will always be at least one underscore you can do this:

var s = "XXXX-XXXX_XX_DigitalF.pdf"

var firstCharAfterUnderscore = s.charAt(s.lastIndexOf("_") + 1);

// OR, with regex

var firstCharAfterUnderscore = s.match(/_([^_])[^_]*$/)[1]

With the regex, you can extract just the one letter by using parentheses to capture that part of the match. But I think the .lastIndexOf() version is easier to read.

Either way if there's a possibility of no underscores in the input you'd need to add some additional logic.

Upvotes: 2

Related Questions