Skip to content Skip to sidebar Skip to footer

Javascript: Selectively Remove Hash (or Hashes) From URLs, So That The URL Remains Valid Or Usable

Say we have the following urls: 1. http://example.com#hash0 2. http://example.com#hash0#hash1 3. http://example.com#hash0/sample.net/ 4. http://example.com#hash0/sample.net/#hash1

Solution 1:

Maybe this what you want, with a regular expression.

var urls = [
        'http://example.com#hash0',                   // remove
        'http://example.com#hash0#hash1',             // remove
        'http://example.com#hash0/sample.net/',       // keep
        'http://example.com#hash0/sample.net/#hash1', // remove #hash1
        'http://example.com#hash0/image.jpg',         // keep
        'http://example.com#hash0/image.jpg#hash1',   // remove #hash1
        'something.php#?type=abc&id=123',             // keep
        'something.php#?type=abc&id=123#hash0',       // remove #hash0
        'something.php/?type=abc&id=#123',            // remove #123
    ],
    result = urls.map(h => h.replace(/(?:#[^#\/\?\.]*)*#[^#\/\?\.]*$/gi, ''));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Post a Comment for "Javascript: Selectively Remove Hash (or Hashes) From URLs, So That The URL Remains Valid Or Usable"