Aleksandar Zoric
Aleksandar Zoric

Reputation: 1483

Remove text before a character but also remove that character

Say I have a string path as follows;

New Folder/New Folder 2/test22.js

I only want the text after the first forward slash, e.g.;

    New Folder 2/test22.js

I tried this;

myText.substring(myText.indexOf('/'))

But I get this. Note the forward slash is still shown.

/New Folder 2/test22.js

This sounds like a simple request but cannot get my head around it.

EDIT Got it working as follows but not sure if this is the best way to go about it;

myText.split(/\/(.+)/)[1]

Upvotes: 0

Views: 95

Answers (4)

Will
Will

Reputation: 320

You could just add 1 to the index the substring is being applied to i.e. myText.substring(myText.indexOf('/') + 1)

Upvotes: 1

r7r
r7r

Reputation: 1525

You can get a substring as below

let myPath = 'New Folder/New Folder 2/test22.js';
let resultPath = myPath.substring(myPath.indexOf('/'));

Upvotes: 1

Scriptkiddy1337
Scriptkiddy1337

Reputation: 791

instead of split and join again, you can search immediately only for the first one

const matches = /.*?\/(.+)/.exec("New Folder/New Folder 2/test22.js");
console.log(matches[1]);

Upvotes: 1

Farid Ansari
Farid Ansari

Reputation: 841

You can also achieve this by using a simple split and join.

x = "New Folder/New Folder 2/test22.js";
x = x.split('/').slice(1).join('/'); // required string.

here,

  1. split('/') will convert it to ["New Folder", "New Folder 2", "test22.js"]
  2. slice(1) to get elements after first element
  3. join('/') to get the required string.

I hope it works for you.

Upvotes: 1

Related Questions