ravan one
ravan one

Reputation: 35

How to remove the last slash content inside JSON

For example the contents of my json would look like{"path": "/home/data/files/access"}. How can I remove /access and replace JSON with {"path": "/home/data/files"}

Upvotes: 0

Views: 550

Answers (3)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can also use split(), pop() and join(). I am adding this answer as an alternative to build logic in javascript.

var obj = {"path": "/home/data/files/access"};
//split to create array
var arr = obj.path.split('/');
//remove last element of array
arr.pop();
//join the elements of array with /
var res = arr.join('/');
//replace the path property of obj
obj.path = res;
console.log(obj);

Upvotes: 0

Faly
Faly

Reputation: 13356

You can split by '/', remove the last element with array.pop then join by '/':

var data = { path: '/home/data/files/access' };
data.path = data.path.split('/');
data.path.pop();
data.path = data.path.join('/');
console.log(data);

Upvotes: 0

flofreelance
flofreelance

Reputation: 944

var obj = {"path": "/home/data/files/access"};
obj.path=obj.path.substring(0, obj.path.lastIndexOf("/"));
console.log(obj);

Upvotes: 2

Related Questions