DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #131 - Remove Anchor from URL

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

Examples

# returns 'www.codewars.com'
remove_url_anchor('www.codewars.com#about')

# returns 'www.codewars.com?page=1'
remove_url_anchor('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!

Top comments (7)

Collapse
 
aminnairi profile image
Amin • Edited

JavaScript

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.

Collapse
 
aminnairi profile image
Amin

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).

benchmark

Collapse
 
thepeoplesbourgeois profile image
Josh

How fast is my implementation?

Thread Thread
 
aminnairi profile image
Amin

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

Collapse
 
thepeoplesbourgeois profile image
Josh
const unAnchor = (url) => url.split("#")[0]

Some comments may only be visible to logged-in visitors. Sign in to view all comments.