DEV Community

loading...

Discussion on: Daily Challenge #305 - Remove Anchors from URLs

Collapse
qm3ster profile image
Mihail Malo

JavaScript

const remove_url_anchor = url => url.split('#', 1)[0]
Enter fullscreen mode Exit fullscreen mode

Second parameter to split means it will stop looking after the first match, and never construct a second string value.

Rust

#![feature(str_split_once)]
fn remove_url_anchor(url: &str) -> &str {
    url.split_once('#').map_or(url, |(x, _)| x)
}
Enter fullscreen mode Exit fullscreen mode

look at it go!

Disclaimer:

In real life, please use developer.mozilla.org/docs/Web/API... or docs.rs/url/ respectively.

These should be fairly bulletproof though, since URL specification doesn't allow unencoded # character anywhere, including notably the <password> section of <protocol>://<user>:<password>@<host>. But where there's fragment, soon will come other parts of the URL.