如何使用Javascript将字符串中的子字符串剪切到最后?

Eri*_*rdt 12 javascript string url

我有一个网址:

http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe
Run Code Online (Sandbox Code Playgroud)

我想使用javascript在最后一次破折号后得到地址:

dashboard.php?page_id=projeto_lista&lista_tipo=equipe
Run Code Online (Sandbox Code Playgroud)

Jas*_*per 25

您可以使用indexOfsubstr获取所需的子字符串:

//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);
Run Code Online (Sandbox Code Playgroud)

strOut变量现在拥有的一切后/dashboard.php(包括字符串).

这是一个演示:http://jsfiddle.net/DupwQ/

文件 -


小智 6

这可能是新的,但substring方法返回从指定索引到字符串末尾的所有内容。

var string = "This is a test";

console.log(string.substring(5));
// returns "is a test"
Run Code Online (Sandbox Code Playgroud)


fru*_*cup 5

如果开头始终是"http:// localhost/40ATV",您可以这样做:

var a = "http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe";
var cut = a.substr(22);
Run Code Online (Sandbox Code Playgroud)