Johan Hirsch Johan Hirsch - 1 year ago 82
Javascript Question

JavaScript RegExp - find all prefixes up to a certain character

I have a string which is composed of terms separated by slashes (

), for example:


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:


I've tried a regex like this:
, but it returns a single match -
with the parenthesized result
, accordingly.


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

Answer Source

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
// => [ "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]);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download