简体   繁体   中英

Extracting very specific part of a string JavaScript

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.

您可以使用标准字符串函数:

var result = s.substring(s.lastIndexOf("_") + 1, s.lastIndexOf("."));

Try this regex:

/_([^_.]*)\.txt$/i

Using String#match :

 var r = 'Hello_World_1_x.txt'.match(/_([^_.]*)\.txt$/)[1];
 //=> x

If you want to use regular expressions, give this a try:

[^_]*(?=\.txt)

正则表达式可视化

Here's a Debuggex Demo and a JSFiddle demo .

There you go:

EDIT: Misread the strings name - now updated:

function getLastValue(string, splitBy) {
  var arr = string.split(splitBy);
  return arr[arr.length-1].split(".")[0]
}


getLastValue("Hello_World_1_x.txt","_"); //"x"
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"

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