给定字符串 '/root/hello/hello/world'
我想提取路径中倒数第二个组件,即hello的第二个出现。
如果不存在父级部分,则希望返回空。因此,字符串/world
应返回一个空字符串或null。
如何使用正则表达式或类似方法提取最后一个路径组件?
语言是javascript。
给定字符串 '/root/hello/hello/world'
我想提取路径中倒数第二个组件,即hello的第二个出现。
如果不存在父级部分,则希望返回空。因此,字符串/world
应返回一个空字符串或null。
如何使用正则表达式或类似方法提取最后一个路径组件?
语言是javascript。
split
方法将字符串转换为数组:var split = '/root/hello/hello/world'.split('/')
-> ["", "root", "hello", "hello", "world"]
var result = split[split.length - 2]
...但您可能需要先检查数组的长度:
var result;
if (split.length >= 2)
result = split[split.length - 2]
您可以做:
let str = '/root/hello/hello/world';
let result = str.split('/');
console.log(result[result.length-2]);
。
([^/\n]*)\/[^/\n]*$
将倒数第二部分捕获到捕获组1中。
([^/\n]*)
部分(括号内)捕获不是 /
或换行符 (\n
) 的一段字符。 \/
确保其后跟着一个 /
,[^/\n]*$
检查该行最后是否以另一个没有 /
(或 LF)的字符串结束。
var pathArray = [
'/root/hello/cruel/world',
'/root/hello/world',
'/root/world',
'/world'
],
re = /([^/\n]*)\/[^/\n]*$/;
pathArray.forEach(function (path) {
document.write( '"' + path + '" returns "' + re.exec(path)[1] + '"<br/>' );
});
你不需要正则表达式,只需要分割它。
const string = '/root/hello/hello/world';
// Split by the '/' character
const stringSplit = string.split('/');
// Slice the array, taking only the last 2 items.
// Then select the first one in the array
const myVal = stringSplit.slice(-2)[0];
// OR, using length
const myValLen = stringSplit[stringSplit.length - 2];
// OR, in one
const myValShort = string.split('/').slice(-2)[0];
"/world/"
怎么样? - Rajesh