1

How can I trim my string which is in this form:

https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg

to this?

media/93939393hhs8.jpeg

I want to remove all the characters before the second to last slash /.

I can use stringByTrimmingCharactersInSet but I don't know how to specify the condition that I want:

let trimmedString = myString.stringByTrimmingCharactersInSet(
  NSCharacterSet.whitespaceAndNewlineCharacterSet() // what here in my case ??
)

The above is for removing the white spaces, but that is not the case here.

2 Answers 2

4

Since the string is an URL get the path components, remove anything but the last 2 items and join the items with the slash separator.

if let url = NSURL(string:"https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg"), pathComponents = url.pathComponents {
  let trimmedString = pathComponents.suffix(2).joinWithSeparator("/")
  print(trimmedString)
}
Sign up to request clarification or add additional context in comments.

4 Comments

@vadian exactly what i needed , thanks a lot , appreciate your effort man
Cool. I knew about NSURLComponents, but not the NSURL property pathComponents. Thanks for teaching me a new trick. (Voted.)
I assume pathComponents trims away things like query strings?
@DuncanC Yes, the path is everything between the host which is xxx.kflslfsk.com in the example and the query (?) separator
1

You're not trimming, you're parsing.

There's no single call that will do what you want. I suggest writing a block of code that uses componentsSeparatedByString("\n") to break it into lines (one URL per line), then parse each line separately.

You could use componentsSeparatedByString("/") on each line to break it into the fragments between your slashes, and then assemble the last 2 fragments together.

(I'm deliberately not writing out the code for you. You should do that for yourself. I'm just pointing you in the right direction.)

You might also be able to use NSURLComponents to treat each line as a URL, but I'm not sure how you'd get the last part of URL before the filename (e.g. "media " or "lego") with that method.

1 Comment

@DunanC seems like my example was not clear enough its just a line of string (see the updated question ) , i putted extra lines for better understanding (it didn't helped though ) I'm just pointing you in the right direction its enough for me thanks for responding :) appreciate your effort man

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.