简体   繁体   English

提取字符串JavaScript的非常具体的部分

[英]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. 我有一个字符串,例如“Hello_World_1_x.txt”,我想在最后一个下划线之后和.txt之前取任何东西。 The .txt will always be there as well as the underscore but there could be many underscores. .txt将始终存在于下划线中,但可能存在许多下划线。 I used .split() to get rid of the last 4 characters but I want only whats after the LAST underscore. 我使用.split()来删除最后4个字符,但我只想在最后一个下划线后才会删除。 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 : 使用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 . 这是Debuggex演示和JSFiddle 演示

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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