Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

javascript - remove everything before the last occurrence of a character

I'm trying to perform the following action on a string :

  • find the last occurrence of the character "/";
  • remove everything before that character;
  • return the remains of the string;

To be more explicit, let's say I have the following string :

var string = "/Roland/index.php"; // Which is a result of window.location.pathname

Now what I need to extract out of it is everything but the actual page, something like this :

var result = "index.php" // Which is what I need to be returned

Of course, that is just an example, because obviously I will have different pages, but the same principles apply.

I was wondering if someone could help me out with a solution for it. I tried the next actions but with no success :

var location = window.location.pathname;
var result = location.substring(location.lastIndexOf["/"]);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have the right idea just replace the brackets with parentheses.

var string = "/Roland/index.php";
var result = string.substring(string.lastIndexOf("/") + 1);

Here is an example in jsfiddle and here is an explanation of the .lastIndexOf() method on the Mozilla Developer Network.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...