0

http://127.0.0.1:8890/demo1/?search=hello%2Cbuddy&Agg=Target+-+All

How do I split the above url and fetch 'search=hello%2Cbuddy' and replace the url as http://127.0.0.1:8890/demo1/?search=goodbye&Agg=Target+-+All

Using javascript I've only reached this far;

var get_url = window.location.href
var parts = get_url.split('/') # doesn't make sense
richie
  • 17,568
  • 19
  • 51
  • 70
  • 1
    What exactly did not work for you referencing http://stackoverflow.com/questions/5413899/search-and-replace-specific-query-string-parameter-value-in-javascript or http://stackoverflow.com/questions/2801970/replacing-strings-with-regex-in-javascript ? – Christopher Will Mar 17 '14 at 14:35
  • 1
    `get_url.replace('hello%2Cbuddy','goodbye')` – Amit Garg Mar 17 '14 at 14:39
  • @AmitGarg I guess the actual searchstring is unknown so a direct replacement would not work here – nils Mar 17 '14 at 15:02

4 Answers4

1

In your case you can replace this part with a simple regular expression:

var url          = document.location.href,
    modified_url = url.replace(/\?search=[^&]+/g, 'search=YOUR_SEARCH_REPLACEMENT');

Replace YOUR_SEARCH_REPLACEMENT with whatever you need there.

nils
  • 1,668
  • 14
  • 15
0

I think this function may be best for you?

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Taken from https://stackoverflow.com/a/901144/2992661

Possibly a duplicate

Community
  • 1
  • 1
Dean Whitehouse
  • 884
  • 1
  • 8
  • 25
0

You could use jQuery URL plugin if you're familiar with jQuery.

ZurabWeb
  • 1,241
  • 1
  • 12
  • 21
0

First, you need to get the Query String, which this post covers: How can I get query string values in JavaScript?

Then you just need to update the url by changing location.href to whatever you want the URL to be.

Community
  • 1
  • 1
Gary Stevens
  • 693
  • 8
  • 20