[英]How to retrieve the last array of characters before a specific string
row1: 10016/Documents/folder1/abc.pdf
row2: 10016-10017/10017/Documents/folder1/folder2/xyz.pdf
I'm trying to retrieve the string before /Documents but if there is any / before, I need to retrieve the string after that我试图在 /Documents 之前检索字符串,但如果之前有任何 / ,我需要在此之后检索字符串
In row 1, I need to retrieve 10016在第 1 行,我需要检索 10016
In row 2, I need to retrieve 10017在第 2 行,我需要检索 10017
I tried我试过
var output = filepath.split("/").slice(0,1);
You can split by '/Documents/', try this:您可以按 '/Documents/' 拆分,试试这个:
let str = '10016/Documents/abc.pdf'; console.log(str.split('/Documents/')[0])
Split by /Documents/
then split that by /
and get the final element:按/Documents/
分割,然后按/
分割并获得最终元素:
const row1 = "10016/Documents/folder1/abc.pdf"; const row2 = "10016-10017/10017/Documents/folder1/folder2/xyz.pdf"; let docs = row1.split("/Documents/")[0]; let nums = docs.split("/"); nums = nums[nums.length - 1]; console.log(nums); docs = row2.split("/Documents/")[0]; nums = docs.split("/"); nums = nums[nums.length - 1]; console.log(nums);
This works for both row1
and row2
as you can see.如您所见,这适用于row1
和row2
。
You can use regular expression to get this你可以使用正则表达式来得到这个
([a-z\d]+)\/Documents
Explaining the regular expression解释正则表达式
+
) occurrence of either an alphabet (az)
or digit (/d)
捕获包含字母(az)
或数字(/d)
一次或多次出现 ( +
) 的所有内容/Documents
phrase还要确保这组字符正好位于/Documents
短语之前 let result = RegExp(/([az\\d]+)\\/Documents/).exec('10016/Documents/abc.pdf'); if (result) { console.log(result[1]) } result = RegExp(/([az\\d]+)\\/Documents/).exec('10016-10017/10017/Documents/xyz.pdf'); if (result) { console.log(result[1]) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.