dend
dend

Reputation: 13

user input to URL

I have some url and I need to replace some parts of it with user input from input type="text" and move to new link with button click.
How can I place variables in URL ?

//some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4

i have function, but it place input at the end of url.

function redirect() {
    var baseUrl = 'http://google.com.ua/';

    document.myform.action=baseUrl + document.getElementById('url').value;
}

<form name="myform" method="post" onsubmit="redirect()">
    <input type="text" id="url">
    <input type="submit" value="submit">
</form>

Upvotes: 0

Views: 431

Answers (3)

naivists
naivists

Reputation: 33551

Played with JavaScript a bit, I believe this solves your problem: http://jsfiddle.net/dk48vwz7/

var linktext = "http://site/some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4";

//we'll use an in-memory "hyperlink" object for basic parsing
var anchor = document.createElement("A");
anchor.href=linktext;

//the query string starts with ?, we remove it. 
//then, split it by & symbol
var queryvars = anchor.search.replace(/^\?/, '').split('&');

//now looping through all parts of query string, creating an object in form key->value
var querycontent = {};
for( i = 0; i < queryvars.length; i++ ) {
    var queryvar = queryvars[i].split('=');
    querycontent[queryvar[0]] = queryvar[1];
}

//this allows us to reference parts of the query as properties of "querycontent" variable
querycontent.service = "AnotherService"
//TODO: change the properties you actually need

//and now putting it all back together
var querymerged = [];
var g = "";
for (var key in querycontent){
    var fragment = key;
    if (querycontent[key]) {
        fragment += "=" + querycontent[key];
    }
    querymerged.push(fragment);
}
anchor.search = querymerged.join("&")

//finally, access the `href` property of anchor to get the link you need
document.getElementById("test").innerText=anchor.href;

Upvotes: 0

Sebastien C.
Sebastien C.

Reputation: 4833

You can use the new URL object (for older browsers, there is a polyfill) :

var url = new URL("http://some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4");
url.searchParams.set("t1", "someNewT1");
url.searchParams.set("t2", "someNewT2");
url.searchParams.set("host", "someNewHost");
url.searchParams.set("service", "someNewService");

alert(url.href);
/*
http://some-url/trends.cgi?host=someNewHost&assumestateretention=yes&initialassumedservicestate=0&t2=someNewT2&initialassumedhoststate=0&assumeinitialstates=yes&zoom=4&backtrack=4&createimage=&assumestatesduringnotrunning=yes&includesoftstates=no&service=someNewService&t1=someNewT1
*/

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50808

You could build out manual query string parsers and constructors, an example would be like:

function parseQuery(qstr){
    var query = {};
    var a = qstr.split('&'); //take the passed query string and split it on &, creating an array of each value
    for (var i in a) { //iterate the array of values
        var b = a[i].split('='); //separate the key and value pair
        query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]); //call decodeURIComponent to sanitize the query string
    }

    return query; //returned the parsed query string object
}

function buildQuery(obj){
    var str = [];
    for(var p in obj) //iterate the query object
       if (obj.hasOwnProperty(p)) { //check if the object has the propery name we're iterating
           str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); //push the encoded key value pair from the object into  the string array
       }
    return str.join("&"); //take the array of key value pairs and join them on &
} 

Then below we take the string that you gave, for example:

var $str = 'createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4';

Now we call the parseQuery function on our string.

var obj = parseQuery($str);

Then we iterate the object which was produced from our parseQuery function

Object.keys(obj).forEach(function(k, i) {
    switch(k){
        case 't1':
            obj[k] = 'replacedt1';
            break;
        case 'service':
            obj[k] = 'replacedServices';
            break;
        case 'host':
            obj[k] = 'replacedHost';
    }         
});

Now the obj variable has the newly updated values. We can rebuild the query using our buildQuery function by passing the object in.

console.log(buildQuery(obj));

Which will produce something like:

createimage=undefined&t1=replacedt1&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=replacedHost&service=replacedServices&backtrack=4&zoom=4 

As usual, the jsFiddle

Upvotes: 1

Related Questions