user2539797
user2539797

Reputation: 75

Javascript string manipulation url

My problem is I am trying to extract certain things from the url. I am currently using

window.location.href.substr()

to grab something like "/localhost:123/list/chart=2/view=1"

What i have now, is using the index positioning to grab the chart and view value.

var chart = window.location.href.substr(-8);
var view = window.location.href.substr(-1);

But the problem comes in with I have 10 or more charts. The positioning is messed up. Is there a way where you can ask the code to get the string between "chart=" and the closest "/"?

Upvotes: 1

Views: 431

Answers (3)

basilikum
basilikum

Reputation: 10528

You could split your string up, with "/" as delimiter and then loop through the resulting array to find the desired parameters. That way you can easily extract all parameters automatically:

var x =  "/localhost:123/list/chart=2/view=1";

var res = {};
var spl = x.split("/");
for (var i = 0; i < spl.length; i++) {
    var part = spl[i];
    var index = part.indexOf("=");
    if (index > 0) {
        res[part.substring(0, index)] = part.substring(index + 1);
    }
}

console.log(res);
// res = { chart: 2, view: 1}

FIDDLE

Upvotes: 1

MDEV
MDEV

Reputation: 10838

var str = "/localhost:123/list/chart=2/view=1";
var data = str.match(/\/chart=([0-9]+)\/view=([0-9]+)/);
var chart = data[1];
var view = data[2];

Of course you may want to add in some validation checks before using the outcome of the match.

Inspired by Paul S. I have written a function version of my answer:

function getPathVal(name)
{
    var path = window.location.pathname;
    var regx = new RegExp('(?:/|&|\\?)'+name+'='+'([^/&,]+)');
    var data = path.match(regx);
    return data[1] || null;
}
getPathVal('chart');//2

Function should work for fetching params from standard get parameter syntax in a URI, or the syntax in your example URI

Upvotes: 3

Paul S.
Paul S.

Reputation: 66304

Here's a way using String.prototype.indexOf

function getPathVar(key) {
    var str = window.location.pathname,
        i = str.indexOf('/' + key + '=') + key.length + 2,
        j = str.indexOf('/', i);
    if (i === key.length + 1) return '';
    return str.slice(i, j);
}
// assuming current path as described in question
getPathVar('chart');

Upvotes: 2

Related Questions