简体   繁体   中英

How to retrieve characters starting from a specific string until last array of characters

row1: 10016/Documents/abc.pdf

row2: 10016-10017/10017/Documents/folder1/folder2/xyz.pdf

I'm trying to retrieve all the characters starting from /Documents but without the last part (file name)

In row 1, I want to retrieve /Documents/

In row 2, I want to retrieve /Documents/folder1/folder2/

I tried

var temp1 = FullPath.split("/Documents/")[0];

var A_Fpath = temp1.split("/");

A_Fpath = A_Fpath[A_Fpath.length - 1];

A simple regex would do the trick:

/\/Documents.*\//
/                    start the regex
 \/                  match literally a "/" (the \ is to escape the / reserved character)
   Documents         match literally the word "Documents" (case sensitive
            .*       match 0 or more characters (any characters)
              \/     match literally a "/"
                /    end the regex
   
This works because regex will attempt to match the longest possible string
of characters that match the regex.

 const row1 = "10016/Documents/abc.pdf"; const row2 = "10016-10017/10017/Documents/folder1/folder2/xyz.pdf"; const regex = /\\/Documents.*\\//; const val1 = row1.match(regex)[0]; const val2 = row2.match(regex)[0]; console.log(val1); console.log(val2);

Here's a Regex101 link to test it out and see more info about this specific regex.

If javascript had a grown-up regular expression engine, one could use a positive, non-capturing lookahead group to determine when to stop.

Since javascript lacks that, the simple, clearer, and more efficient way is to not use a regular expression at all. The algorithm is simple:

  • Find the [first/leftmost] /Documents in the source text, then

  • Find the last/rightmost occurrence of / in the source text

  • Deal with the two special cases where:

    • The source string doesn't contain /Documents at all, and
    • The rightmost / is the / in /Documents
  • Failing a special case as noted above, return the desired substring extending from /Documents up to and including the last /

Like this:

function getInterestingBitsFrom(path) {
  const i   = path.indexOf('/Documents');
  const j   = path.lastIndexOf('/');
  const val = i < 0   ? undefined     // no '/Documents' in string
            : i === j ? path.slice(i) // last '/' in string is the '/' in '/Documents'             
            : path.slice(i, j+1)      // '/Documents/' or '/Documents/.../'
            ;

  return retVal;  
}

This also has the laudatory benefit of being easy to understand for someone who has to figure out what you were trying to accomplish.

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