SooCheng Koh February 2016

Extract part of path from full path Javascript

How can I extract

pathB/pathC/pathD

from

pathA/pathB/pathC/pathD/data.json

welcome any third party library or plain javascript

In some loader of webpack such as ng-cache-loader, I found they are able to strip the middle part of a path by specifying '//'.

From ng-cache-loader Docs:

Prefix can strip the real directory name (use //):

require('ng-cache?prefix=public/*//*/templates!./far/far/away/path/to/myPartial.html')
// => ng-include="'public/far/path/templates/myPartial.html'"  

I can't find any code that process the path in ng-cache-loader source code. Maybe I can use the same way they did to strip the middle part of path?

Answers


Zonedark February 2016

I approached your problem as a string parsing one, as mzografski mentionned. You can check this working JSFIDDLE

Code :

$scope.ToExtract = 'pathB/pathC/pathD';
$scope.test = 'pathA/pathB/pathC/pathD/data.json';

$scope.extract = function(partToExtract, fullPath) {
    var index = fullPath.indexOf(partToExtract);
    return(fullPath.substring(0, index) + fullPath.substring(index+partToExtract.length+1, fullPath.length));
};

$scope.extract($scope.ToExtract, $scope.test);


SooCheng Koh February 2016

var sep = '/';
var path = 'pathA/pathB/pathC/pathD/data.json';
path = path.split(sep);
path.shift();
path.pop();
path = path.join(sep);

// log pathB/pathC/pathD
console.log(path);

Post Status

Asked in February 2016
Viewed 2,949 times
Voted 13
Answered 2 times

Search




Leave an answer