-1

This sounds easy, but I am stumped. The syntax and functions of Range are very confusing to me.

I have a URL like this:

https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post

I need to extract the part #global-best-time-to-post, essentially the # to the end of the string.

urlString.rangeOfString("#") returns Range Then I tried doing this assuming that calling advanceBy(100) would just go to the end of the string but instead it crashes.

hashtag = urlString.substringWithRange(range.startIndex...range.endIndex.advancedBy(100))
rmaddy
  • 314,917
  • 42
  • 532
  • 579
shakked
  • 783
  • 8
  • 24

3 Answers3

4

Easiest and best way to do this is use NSURL, I included how to do it with split and rangeOfString:

import Foundation

let urlString = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"

// using NSURL - best option since it validates the URL
if let url = NSURL(string: urlString),
  fragment = url.fragment {
  print(fragment)
}
// output: "global-best-time-to-post"

// using split - pure Swift, no Foundation necessary
let split = urlString.characters.split("#")
if split.count > 1,
  let fragment = split.last {
  print(String(fragment))
}
// output: "global-best-time-to-post"

// using rangeofString - asked in the question
if let endOctothorpe = urlString.rangeOfString("#")?.endIndex {
  // Note that I use the index of the end of the found Range 
  // and the index of the end of the urlString to form the 
  // Range of my string
  let fragment = urlString[endOctothorpe..<urlString.endIndex]
  print(fragment)
}
// output: "global-best-time-to-post"
1

You could also use substringFromIndex

let string = "https://github.com..."
if let range = string.rangeOfString("#") {
  let substring = string.substringFromIndex(range.endIndex)
}

but I'd prefer the NSURL way.

vadian
  • 274,689
  • 30
  • 353
  • 361
-1

use componentsSeparatedByString method

let url = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
let splitArray = url.componentsSeparatedByString("#")

your required last text phrase (without # char) will be at the last index of the splitArray , you can concatenate the # with your phrase

var myPhrase = "#\(splitArray[splitArray.count-1])"
print(myPhrase)
Qadir Hussain
  • 8,721
  • 13
  • 89
  • 124