Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting fields from a url in scala-js

Tags:

scala.js

Suppose I've a url like :

https://example.com/myproject/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all

or it may be a webpage on localhost like :

localhost:63342/my project/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all

and I've to extract query fields (appearing after '?') from these urls in 2-D array as following :

_ijt    |    hsdlgh8h5g8hh489sajoej
a       |    102
b       |    a m
c       |    45
d       |    all
e       |    all

Please do note that in 'b' field, I've replaced '%20' with a space. These fields like _ijt,a,b,c,d,e etc can vary in number and their names eg 'a' can be 'city'. So far I've used regular expression to extract out the part after '?' and then use split("&") method to split the string into multiple strings. Code -

val url=localhost:63342/my project/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all
val pattern="""(http|htpps)([A-Za-z0-9\:\/\%\-\.]*)\?""".r
val temp_url=pattern.replaceFirstIn(url,"")
val fields=temp_url.split("&")
println(fields.foreach(println))

and the output is :

_ijt=hsdlgh8h5g8hh489sajoej
a=102
b=a%20m
c=45
d=all
e=all

But it doesn't seem to be the correct way to do this. Any help ?

like image 969
Ishan Avatar asked Mar 10 '23 11:03

Ishan


2 Answers

Use js.URIUtils.decodeURIComponent to accurately decode the %-encoded characters.

like image 143
sjrd Avatar answered Apr 27 '23 09:04

sjrd


You need to call js.URIUtils.decodeURIComponent on query parameter values:

val fields=temp_url.split("&").map(js.URIUtils.decodeURIComponent)

decodeURIComponent is a native Javascript function, for which scala.js has a simple interface.

Alternatively, you could use some library for parsing URLs written in Scala. Parsing URLs is often a security hazard, and it's easy to make a mistake. Libraries also typically support any input that satisfies the relevant Standards / RFCs.

like image 38
Nikita Avatar answered Apr 27 '23 08:04

Nikita