开发者

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?


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


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

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";


You could use a regular expression like this one:

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

A string’s match method gives you either an array (of the whole match, in this case the whole input, and of any capture groups (and we want the first capture group)), or null. So, for general use you need to pull out the 1th element of the array, or null if a match wasn’t found:

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


let str = "http://blablab/test";
let data = new URL(str).pathname.split("/").pop();
console.log(data);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜