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

时间:2012-03-13 20:12:21

标签: javascript string url

我有一个网址:

http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe

我希望在最后一次破折号后使用javascript获取地址:

dashboard.php?page_id=projeto_lista&lista_tipo=equipe

7 个答案:

答案 0 :(得分:26)

您可以使用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);

strOut变量现在保存/dashboard.php之后的所有内容(包括该字符串)。

以下是演示:http://jsfiddle.net/DupwQ/

文档 -

答案 1 :(得分:5)

如果开头总是“http:// localhost / 40ATV”,你可以这样做:

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

答案 2 :(得分:4)

原生JavaScript字符串方法substr [MDN] 可以完成您的需要。只需提供起始索引并省略length参数,它就一直抓到最后。

现在,如何获得起始索引?你没有给出任何标准,所以我无法真正帮助你。

答案 3 :(得分:4)

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

var string = "This is a test";

console.log(string.substring(5));
// returns "is a test"

答案 4 :(得分:2)

不需要jQuery,普通的旧javascript就可以完成这项工作。

var myString = "http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe";
var mySplitResult = myString.split("\/");
document.write(mySplitResult[mySplitResult.length - 1]);​

如果你想要领先/

document.write("/" + mySplitResult[mySplitResult.length - 1]);​

答案 5 :(得分:0)

首先 SPLIT 网址:

var str = "http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe";
var arr_split = str.split("/");

找到最后一个数组:

var num = arr_split.length-1;

您在最后一次破折号后获得地址:

alert(arr_split[num]);

答案 6 :(得分:0)

如果没有dashboard...返回空,则可以使用此代码。

var str = 'http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe';
var index = str.indexOf('/dashboard.php') + 1;
var result = '';
if (index != 0) {
  result = str.substr(index);
}
console.log(result);

相关问题