0

input:

"/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"

javascript:

var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
var parts = parmeters.split('[&=]');

output of my js code:

0: "passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
length: 1

i want to split my url into a map with key:value like this

output:

origin:THR
destination:TDR
goDate:2015-01-09
passengers:STANDARD:1
returnDate:2015-01-10
max:0
withThac:false

My code not do exactly what i want in output, what is wrong ?

2
  • the is no '[&=]' found on the split so this is the expected behavior Commented Jan 9, 2015 at 10:15
  • 1
    You are using a string that contains 4 characters [&=] as a delimiter to split. Since the input does not contain [&=] you're getting only one big string as your result. Try putting it in a regular expression like ...split(/[&=]/). This stackoverflow.com/a/3560051/1389366 is a very nice explanation to your problem. Commented Jan 9, 2015 at 10:15

3 Answers 3

2

You should split with

var params = parmeters.split('&')

and then split all the values you get

for (var i = 0,len = params.length; i<len;i++){
    var data = params[i].split("=", 2);  // Max 2 elements

    var key = data[0];
    var value = data[1];
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

i think your wrong ' characters

var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
/*--> i think used regexp. Clear ' Char. --> */var parts = parmeters.split(/[&=]/);

use this like..

good luck

Comments

1

A possible solution using ECMA5 methods and assuming that your string is always the same pattern.

var src = '/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false',
    slice = src.split(/[\/|?|&]/).slice(3),
    data = slice.reduce(function (output, item) {
        var split = item.split('=');

        output[split.shift()] = split.shift();

        return output;
    }, {
        origin: slice.shift(),
        destination: slice.shift(),
        goDate: slice.shift()
    });

document.body.appendChild(document.createTextNode(JSON.stringify(data)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.