Looking for the easiest way to extract an unknown substring from within a string. (terms separated by slashes)

Viewed 79

The initial string:
initString = '/digital/collection/music/bunch/of/other/stuff'

What I want:
music

  • Specifically, I want any term (will never include slashes) that would come between collection/ and /bunch

How I'm going about it:

if(initString.includes('/digital/collection/')){
    let slicedString = initString.slice(19); //results in 'music/bunch/of/other/stuff'
    let indexOfSlash = slicedString.indexOf('/'); //results, in this case, to 5
    let desiredString = slicedString.slice(0, indexOfSlash); //results in 'music'
}

Question:
How the heck do I accomplish this in javascript in a more elegant way?

  • I looked for something like an endIndexOf() that would replace my hardcoded .slice(19)
    • lastIndexOf() isn't what I'm looking for, because I want the index at the end of the first instance of my substring /digital/collection/
  • I'm looking to keep the number of lines down, and I couldn't find anything like a .getStringBetween('beginCutoff, endCutoff')

Thank you in advance!

7 Answers

your title says "index" but your example shows you wanting to return a string. If, in fact, you are wanting to return the string, try this:

if(initString.includes('/digital/collection/')) {
    var components = initString.split('/');
    return components[3]; 
}

If the path is always the same, and the field you want is the after the third /, then you can use split.

var initString = '/digital/collection/music/bunch/of/other/stuff';
var collection = initString.split("/")[2]; // third index

In the real world, you will want to check if the index exists first before using it.

var collections = initString.split("/");
var collection = "";
if (collections.length > 2) {
    collection = collections[2];
}

You can use const desiredString = initString.slice(19, 24); if its always music you are looking for.

If you need to find the next path param that comes after '/digital/collection/' regardless where '/digital/collection/' lies in the path

  1. first use split to get an path array
  2. then use find to return the element whose 2 prior elements are digital and collection respectively

const initString = '/digital/collection/music/bunch/of/other/stuff'

const pathArray = initString.split('/')

const path = pathArray.length >= 3 
    ? pathArray.find((elm, index)=> pathArray[index-2] === 'digital' && pathArray[index-1] === 'collection')
    : 'path is too short'

console.log(path)

Think about this logically: the "end index" is just the "start index" plus the length of the substring, right? So... do that :)

const sub = '/digital/collection/';
const startIndex = initString.indexOf(sub);
if (startIndex >= 0) {
    let desiredString = initString.substring(startIndex + sub.length);
}

That'll give you from the end of the substring to the end of the full string; you can always split at / and take index 0 to get just the first directory name form what remains.

You can also use regular expression for the purpose.

const initString = '/digital/collection/music/bunch/of/other/stuff';
const result = initString.match(/\/digital\/collection\/([a-zA-Z]+)\//)[1];
console.log(result);

The console output is:

music

If you know the initial string, and you have the part before the string you seek, then the following snippet returns you the string you seek. You need not calculate indices, or anything like that.

// getting the last index of searchString
// we should get: music
const initString = '/digital/collection/music/bunch/of/other/stuff'
const firstPart = '/digital/collection/'


const lastIndexOf = (s1, s2) => {
  return s1.replace(s2, '').split('/')[0]
}

console.log(lastIndexOf(initString, firstPart))

Related