Erick Engelhardt Erick Engelhardt -4 years ago 106
Javascript Question

How can I cut a substring from a string to the end using Javascript?

I have a url:


I want to get the address after the last dash using javascript:


Answer Source

You can use indexOf and substr to get the sub-string you want:

//using a string variable set to the URL you want to pull info from
//this could be set to `window.location.href` instead to get the current URL
var strIn  = 'http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe',

    //get the index of the start of the part of the URL we want to keep
    index  = strIn.indexOf('/dashboard.php'),

    //then get everything after the found index
    strOut = strIn.substr(index);

The strOut variable now holds everything after /dashboard.php (including that string).

Here is a demo:

Docs -

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download