How can I remove all characters up to and including the 3rd slash in a string?
To get the last item in a path, you can split the string on /
and then pop()
:
var url = "http://blablab/test";
alert(url.split("/").pop());
//-> "test"
To specify an individual part of a path, split on /
and use bracket notation to access the item:
var url = "http://blablab/test/page.php";
alert(url.split("/")[3]);
//-> "test"
Or, if you want everything after the third slash, split()
, slice()
and join()
:
var url = "http://blablab/test/page.php";
alert(url.split("/").slice(3).join("/"));
//-> "test/page.php"
var string = 'http://blablab/test'
string = string.replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'')
alert(string)
This is a regular expression. I will explain below
The regex is /[\s\S]*\//
/
is the start of the regex
Where [\s\S]
means whitespace or non whitespace (anything), not to be confused with .
which does not match line breaks (.
is the same as [^\r\n]
).
*
means that we match anywhere from zero to unlimited number of [\s\S]
\/
Means match a slash character
The last /
is the end of the regex
var str = "http://blablab/test";
var index = 0;
for(var i = 0; i < 3; i++){
index = str.indexOf("/",index)+1;
}
str = str.substr(index);
To make it a one liner you could make the following:
str = str.substr(str.indexOf("/",str.indexOf("/",str.indexOf("/")+1)+1)+1);