How can I delete all characters up to the 3rd braid in one line?

I'm having trouble deleting all characters before the 3rd slash in JavaScript. This is my line:

http://blablab/test 

The result should be:

 test 

Does anyone know the right solution?

+5
javascript string
source share
5 answers

To get the last item in the path, you can split the string into / and then pop() :

 var url = "http://blablab/test"; alert(url.split("/").pop()); //-> "test" 

To specify a separate part of the path , divide by / and use the parenthesis entry to access the element:

 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" 
+17
source share
 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

Regular expression /[\s\S]*\//

/ is the beginning of a regular expression

If [\s\S] means a space or non-empty space (nothing), you should not be confused with . which does not match line breaks ( . matches the [^\r\n] ).

* means that we match anywhere from zero to an unlimited number [\s\S]

\/ The tool matches the slash character

The last / is the end of the regex

+2
source share
 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 do this with one liner, you can do the following:

 str = str.substr(str.indexOf("/",str.indexOf("/",str.indexOf("/")+1)+1)+1); 
+2
source share

You can use split to split the line in parts and use slice to return all parts after the third fragment.

 var str = "http://blablab/test", arr = str.split("/"); arr = arr.slice(3); console.log(arr.join("/")); // "test" // A longer string: var str = "http://blablab/test/test"; // "test/test"; 
0
source share

You can use a regex like this:

 'http://blablab/test'.match(/^(?:[^/]*\/){3}(.*)$/); // -> ['http://blablab/test', 'test] 

The match string method gives you either an array (all matches, in this case all input, and all capture groups (and we want the first capture group)), or null. So, for general use, you need to pull out the 1st element of the array or null if no match is found:

 var input = 'http://blablab/test', re = /^(?:[^/]*\/){3}(.*)$/, match = input.match(re), result = match && match[1]; // With this input, result contains "test" 
0
source share

All Articles