Mohan Gopi Mohan Gopi - 1 year ago 32
Javascript Question

How to split a string and make particular data only to be stored in a variable

I have a string like

var directoryPath = "file:///storage/sdcard0/Android/data/com.ionicframework.ftptranfer949961/cache/1467013143014.png"

in the above variable I would like storing only a particular string like this

var updatedPath = "/storage/sdcard0/Android/data/com.ionicframework.ftptranfer949961/cache/"

I have tried the
method but I don't know how to store the particular path in my updatedPath variable.

Answer Source

What you could do is something like this:

var directoryPath = "file:///storage/sdcard0/Android/data/com.ionicframework.ftptranfer949961/cache/1467013143014.png";
var stringToReplace = 'file://';
var lastIndexOfSlash = directoryPath.lastIndexOf('/');
var offset = stringToReplace.length;
var updatedPath = directoryPath.substr(offset, lastIndexOfSlash - offset + 1);

This will set the updatePath variable to the directoryPath withouth the string you wish to remove (i.e. "file://") and remove the last part of the url where the .png location is set.