Profstyle
Profstyle

Reputation: 444

how to explode an url in javascript

I would like to remove "/first" string and remove _1_1_1 at the end of the url.

/foo/blah/tree/first/image_pack-1-1-1

what i need to turn is

/foo/blah/tree/image_pack

Here's what I have done but doesn't work as i wish. I'm stuck at some point.

var fileUrl = "/foo/blah/tree/first/image_pack-1-1-1";
var output = fileUrl.split(/[/ ]+/).pop();
var explode = output.split("-");
console.log(explode[0]);

Upvotes: 0

Views: 1042

Answers (3)

somethinghere
somethinghere

Reputation: 17358

The question on everyone's mind is: how recurring is this? Is first a variable? Is 1-1-1-1 always at the end? If both of them are constant, then it's easy:

fileUrl.split('-')[0].replace('first/','')

But otherwise, you might be better off constructing a function for it:

function fileUrl(url, replacements){
    // Allow for replacements to be empty
    replacements = replacements || [];
    // Split at the `-` - a more versatile way would be too complex here.
    url = url.split('-')[0];
    for(var i = 0; i < replacements.length; i++){
        url = url.replace(replacements[i], '');
    }
    // Remove any double slashes that have accumulated
    while(url.indexOf('//').length >= 0) url.replace('//','/');
    return url;
}

Now you can easily do this:

fileUrl('/foo/blah/tree/first/image_pack-1-1-1', ['first']);

function fileUrl(url, replacements){
        replacements = replacements || [];
        url = url.split('-')[0];
        for(var i = 0; i < replacements.length; i++){
            url = url.replace(replacements[i], '');
        }
        while(url.indexOf('//').length >= 0) url.replace('//','/');
        return url;
    }

document.write(fileUrl('/foo/blah/tree/first/image_pack-1-1-1', ['first']));

Upvotes: 1

Andy
Andy

Reputation: 63589

Not sure you can realistically get there in one line. How about this. It splits against the first dash, splits the first element against the backslashes, and then splices that 4th element right out regardless of what it's called. Then just join it back together.

var output = fileUrl.split('-')[0].split('/');
output.splice(4, 1);
output = output.join('/'); // /foo/blah/tree/image_pack

DEMO

Upvotes: 1

indubitablee
indubitablee

Reputation: 8216

would something like this work?

var fileUrl = "/foo/blah/tree/SOMERANDOMTHINGREMOVEDHERE/image_pack-1-1-1";
var newUrl1 = fileUrl.split('-')[0].split('/');
console.log(newUrl1);
var finalUrl = '';
for(var i = 0; i < newUrl1.length; i++) {
    if (i != 4) {
        finalUrl += newUrl1[i] + '/';
    }
}
alert(finalUrl);

Upvotes: 0

Related Questions