Daily Challenge #131 - Remove Anchor from URL

thepracticaldev profile image dev.to staff ・1 min read

Complete the function/method so that it returns the URL with anything after the anchor (#) removed.


# returns 'www.codewars.com'

# returns 'www.codewars.com?page=1'

This challenge comes from jhoffner on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!


Editor guide


Recursive solution with runtime type checking.

function removeUrlAnchor(url) {
    if (arguments.length !== 1) {
        throw new Error("expected exactly one argument");

    if (typeof url !== "string") {
        throw new TypeError("expect first argument to be a string");

    if (url.length === 0) {
        return "";

    const [character, ...remainingUrl] = url;

    if (character === "#") {
        return "";

    return character + removeUrlAnchor(remainingUrl.join(""));

Try it.


I just did several modifications to the algorithm to find the fastest solution in JavaScript using JSPerf. Turns out, the fastest way to get this done is by doing this:

function removeUrlAnchor(url) {
    const index = url.indexOf("#");

    return index === -1 ? url : url.slice(0, index);

I also removed the runtime type checking for the tests.

Tests are available here (tested in Chromium only).



Hi Josh. You could use JSPerf to test your code. It is really simple to get up and running your own benchmarks.

const unAnchor = (url) => url.split("#")[0]

The what now? Took me a minute to figure out what this even was...

You're using the wrong terminology. An Anchor is a point on the page that can be linked to or links to another part of the page. Hence the tag <A>nchor.

The number sign in a URI (and yes, it becomes a URI not URL at that point) is called a hash. Everything after the hash is called a "fragment identifier".

... might also help if it said where people are supposed to submit answers. Just post 'em here? Go to the painfully inaccessible codewars? (talk about WCAG violations; sorry, accessibility is my day job)

Though in answering this I'd be really broken between splitting the string with a limit of 2 and throwing away the latter half, or screwing around with strpos and substr. In any valid URI there should only be one # anyways.


You wouldn't even need to limit the split to 2 entries. Maybe it yields a performance improvement, but it should be negligible in all but the hashiest of string cases