繁体   English   中英

如何使用Javascript将子字符串从字符串切到结尾?

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

我有一个网址:

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

我想使用javascript获取最后一个破折号后的地址:

dashboard.php?page_id=projeto_lista&lista_tipo=equipe

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

更新:

上面示例中的strOut变量包含前缀的正斜杠,因此要求输出不应该包含该斜杠。

strOut = strIn.substr(index)替换strOut = strIn.substr(index) strOut = strIn.substr(index + 1) ,可通过从子字符串开始在字符串中更远的一个字符开始,来固定此特定用例的输出。

您可以做的另一件事是在特定搜索词(不包括在内)之后搜索字符串:

var strIn = 'http://localhost/40ATV/dashboard.php?page_id=projeto_lista&lista_tipo=equipe';
var searchTerm = '/dashboard.php?';
var searchIndex = strIn.indexOf(searchTerm);
var strOut = strIn.substr(searchIndex + searchTerm.length); //this is where the magic happens :)

strOut现在拥有的一切后/dashboard.php? (非包容性)。

这是一个更新的演示: http : //jsfiddle.net/7ud0pnmr/1/

文件-

如果开头始终是“ http:// localhost / 40ATV”,则可以执行以下操作:

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

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

var string = "This is a test";

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

原生JavaScript String方法substr [MDN] substr您的需求。 只需提供起始索引并省略length参数,它就一直抓到结尾。

现在,如何开始获取起始索引? 您没有提供任何标准,因此我对此无能为力。

不需要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]);​

首先是SPLIT URL:

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]);

如果没有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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM