1

I have two URLS of the type :

val url = "../../a/b/c.html"

val parentURL = "http://www.someurl.com/section1/section2/section3.html"

What I am looking to do is to produce a resulting String as follow :

val resultingString = "http://www.someurl.com/section1/a/b/c.html"

I can count the occurrences of ".." in the first URL, but I have no idea how to use it to kind of "substring" the parentURL the way I want.

Any help ?

2 Answers 2

6

Handling URLs is messy with all kinds of exceptions. I recommend using the methods provided by the JVM to handle this.

val parsed = new java.net.URL(parentURL)
new URL(
  parsed.getProtocol,
  parsed.getHost,
  parsed.getPort,
  java.nio.file.Paths.get(parsed.getFile, url).normalize.toString)
2

You could use the standard functions of Scala as follows if you want to parse it yourself:

val parts = url.split('/').foldLeft(parentURL.split('/')) { case (cur, dir) =>
  if (dir == ".") cur // stay in current directory
  else if (dir == "..") cur.dropRight(1) // go up in the tree
  else cur :+ dir // cd into directory
}

parts.mkString("/") // build the string back

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.