1

I want to get the substring of all the characters after the last index of /

for example: "www.example.com/sfs3/dd/423"

desired output = 423

I've tried:

if let range = link.rangeOfString("/") { //does not give me the last index of / it gives me starting from the first / newlink = link.substringFromIndex(range.endIndex) } 

2 Answers 2

6

You could also use NSURL's -lastPathComponent:

let link = "www.example.com/sfs3/dd/423" if let url = NSURL(string: link) { let newLink = url.lastPathComponent // ... } 

This is probably the most bullet proof way if your input is a URL, be it from the web or from a local file.

Sign up to request clarification or add additional context in comments.

Comments

5

With your syntax you can use the .BackwardsSearch option

if let range = link.rangeOfString("/", options: .BackwardsSearch) { let newlink = link.substringFromIndex(range.endIndex) } 

Alternatively

if let newlink = link.componentsSeparatedByString("/").last { print(newlink) } 

Edit: But I'd prefer the NSURL solution suggested by fabian.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.