简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM