I have a string for example "Hello_World_1_x.txt" and I want to take what ever is after the last underscore and before the .txt. The .txt will always be there as well as the underscore but there could be many underscores. I used .split() to get rid of the last 4 characters but I want only whats after the LAST underscore. So far my regex only gives me whats after the first underscore.
5 Answers
If you want to use regular expressions, give this a try:
[^_]*(?=\.txt)

Here's a Debuggex Demo and a JSFiddle demo.
Comments
var s = "Hello_World_1_x.txt";
var a = s.split(/[._]/);
console.log( a[a.length-2] ); // "x"
This says, "Split the string on either periods or underscores, and then pick the part that is next-to-last"". Alternatively:
var s = "Hello_World_1_x.txt";
var a = s.split(/[._]/);
a.pop(); var last = a.pop();
console.log( last ); // "x"