Search code examples
javascriptstringsplitsubstringtrim

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!!!


Solution

  • 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