Enrique GF
Enrique GF

Reputation: 1295

Removing elements of string before a specific repeated character in it in javascript

I'm trying to remove from my string all elements before an specific character which is repeated several times in this way:

let string = http://localhost:5000/contact-support

thus I´m just trying to remove everything before the third / having as result:contact_support

for that i just set:

string.substring(string.indexOf('/') + 3);

Bust guess thats not the correct way

Any help about how to improve this in the simplest way please? Thanks in advance!!!

Upvotes: 0

Views: 244

Answers (4)

Adarsh Niket
Adarsh Niket

Reputation: 1

string.substring(string.lastIndexOf('/')+1) will also do the job if you are looking to use indexOf function explicitly.

Upvotes: 0

Iziminza
Iziminza

Reputation: 389

You could also use lastIndexOf('/'), like this:

string.substring(string.lastIndexOf('/') + 1);

Another possibility is regular expressions:

string.match(/[^\/]*\/\/[^\/]*\/(.*)/)[1];

Note that you must escape the slash, since it is the delimiter in regular expressions.

Upvotes: 0

Freeman Lambda
Freeman Lambda

Reputation: 3655

It seems like you want to do some URL parsing here. JS brings the handful URL utility which can help you with this, and other similar tasks.

const myString = 'http://localhost:5000/contact-support';

const pathname = new URL(myString).pathname;

console.log(pathname); // outputs: /contact-support

// then you can also remove the first "/" character with `substring`
const whatIActuallyNeed = pathname.substring(1, pathname.length);

console.log(whatIActuallyNeed); // outputs: contact-support

Upvotes: 2

Ahmmed Abir
Ahmmed Abir

Reputation: 189

Hope This will work

string.split("/")[3]

It will return the sub-string after the 3rd forward slash.

Upvotes: 0

Related Questions