regex - JavaScript RegExp - find all prefixes up to a certain character -
i have string composed of terms separated slashes ('/'
), example:
ab/c/def
i want find prefixes of string occurrence of slash or end of string, i.e. above example expect get:
ab ab/c ab/c/def
i've tried regex this: /^(.*)[\/$]/
, returns single match - ab/c/
parenthesized result ab/c
, accordingly.
edit :
i know can done quite using split
, looking solution using regexp
.
no, can't pure regex.
why? because need substrings starting @ 1 , same location in string, while regex matches non-overlapping chunks of text , advances index search match.
ok, capturing groups? helpful if know how many /
-separated chunks have in input string. use
var s = 'ab/c/def'; // there exact 3 parts console.log(/^(([^\/]+)\/[^\/]+)\/[^\/]+$/.exec(s)); // => [ "ab/c/def", "ab/c", "ab" ]
however, unlikely know many details input string.
you may use following code rather 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, can split string /
. then, iterate through elements , build res
array.
Comments
Post a Comment