Search code examples
javascriptregexprefix

JavaScript RegExp - find all prefixes up to a certain character


I have a string which is composed of terms separated by slashes ('/'), for example:

ab/c/def

I want to find all the prefixes of this string up to an occurrence of a slash or end of string, i.e. for the above example I expect to get:

ab
ab/c
ab/c/def

I've tried a regex like this: /^(.*)[\/$]/, but it returns a single match - ab/c/ with the parenthesized result ab/c, accordingly.

EDIT :

I know this can be done quite easily using split, I am looking specifically for a solution using RegExp.


Solution

  • NO, you can't do that with a pure regex.

    Why? Because you need substrings starting at one and the same location in the string, while regex matches non-overlapping chunks of text and then advances its index to search for another match.

    OK, what about capturing groups? They are only helpful if you know how many /-separated chunks you have in the input string. You could then use

    var  s = 'ab/c/def'; // There are exact 3 parts
    console.log(/^(([^\/]+)\/[^\/]+)\/[^\/]+$/.exec(s));
    // => [ "ab/c/def", "ab/c", "ab" ]

    However, it is unlikely you know that many details about your input string.

    You may use the following code rather than a regex:

    var  s = 'ab/c/def';
    var chunks = s.split('/');
    var res = [];
    for(var i=0;i<chunks.length;i++) {
      res.length > 0 ? res.push(chunks.slice(0,i).join('/')+'/'+chunks[i]) : res.push(chunks[i]);
    }
    console.log(res);

    First, you can split the string with /. Then, iterate through the elements and build the res array.