Home > database >  Javascript extract string from start to 0/, removing anything after 0/
Javascript extract string from start to 0/, removing anything after 0/

Time:04-19

I have a string which looks like this:

file:///storage/emulated/0/Pictures/IMG212.jpg

I want to remove anything from Pictures onwards so I would get this:

file:///storage/emulated/0/

How can I do this?

CodePudding user response:

var regex = /^.*0\//
var matches = str.match(regex);
console.log(matches[0]);

CodePudding user response:

You could find the index of /0 and use substring to select everything up to that point, like so:

const line = "file:///storage/emulated/0/Pictures/IMG212.jpg";

// Get the location of "/0", will be 24 in this example
const endIndex = line.indexOf("/0");

// Select everything from the start to the endIndex   2
const result = line.substring(0, endIndex 2);

The reason why we add 2 to the endIndex is because the string that we're trying to find is 2 characters long:

file:///storage/emulated/0/Pictures/IMG212.jpg
                  [24]--^^--[25]

CodePudding user response:

You can split the string using split method:

const myString = "file:///storage/emulated/0/Pictures/IMG212.jpg";
const result = myString.split("0/")[0]   "0/";
console.log(result);    // file:///storage/emulated/0/

documentation for split method on MDN

  • Related