Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all characters up to and including the 3rd slash in a string?

I'm having trouble with removing all characters up to and including the 3 third slash in JavaScript. This is my string:

http://blablab/test

The result should be:

test

Does anybody know the correct solution?

like image 335
Frank Avatar asked May 11 '11 14:05

Frank


2 Answers

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"
like image 193
Andy E Avatar answered Sep 21 '22 21:09

Andy E


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

like image 33
700 Software Avatar answered Sep 22 '22 21:09

700 Software