Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Replace Specified Part of QueryString With JavaScript

Posted on 2004-08-03
6
203 Views
Last Modified: 2012-08-14
I need a function which will replace a given part of a querystring. The function needs to look like this:

function replaceQueryStringPart(url, name, value) {
    ...
}

It needs to work as follows:

replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'name', 'fred') //Returns http://localhost/test.asp?name=fred&phone=12345

replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'phone', '67890') //Returns http://localhost/test.asp?name=brian&phone=67890

If the specified querystring part does not exist, it must be appended to the end of the querystring as follows:

replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'email', 'test@server.com') //Returns http://localhost/test.asp?name=brian&phone=67890&email=test@server.com

replaceQueryStringPart('http://localhost/test.asp', 'email', 'test@server.com') //Returns http://localhost/test.asp?email=test@server.com

I have spent a few hours on this now and realised I need to use the JavaScript RegExp object with the replace method, but I can't get my head around regular expressions enough to write the function. Would be very grateful for any assistance.

-William
0
Comment
Question by:wwarby
  • 4
  • 2
6 Comments
 
LVL 63

Expert Comment

by:Zvonko
ID: 11705431
I used a small trick, but what do you think of this:

<script>
function replaceQueryStringPart(theUrl, theParam, theValue){
   theUrl = theUrl.replace(new RegExp("[\\?\\&]?"+theParam+"\\=[^\\&]+","i"),"");
   if(theUrl.indexOf("?")>-1){
     return theUrl+"&"+theParam+"="+theValue
   } else {
     return theUrl+"?"+theParam+"="+theValue
   }
}

alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'name', 'fred'));
alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'phone', '67890'));
alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'email', 'test@server.com'));
alert(replaceQueryStringPart('http://localhost/test.asp', 'email', 'test@server.com'));
</script>



0
 
LVL 1

Author Comment

by:wwarby
ID: 11712702
It's almost there, except the first alert box returns 'http://localhost/test.asp&phone=12345?name=fred', which isn't correct syntax. I'll have a look at what you've done and see if I can fix it myself - if you have any suggestions I'd be really grateful. Other than that, it's exactly what I wanted. These regular expressions seem like an impenetrable encrypted language to me - I've read three tutorials and am no closer to understanding them.

-William
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 11713275
Uhps sorry. I did not test it well.

Here the revised version:
<script>
function replaceQueryStringPart(theUrl, theParam, theValue){
   theUrl = theUrl.replace(new RegExp("\\&?"+theParam+"\\=[^\\&]+","i"),"");
   theUrl = theUrl.replace("?&","?");
   if(theUrl.indexOf("?")>-1){
     return theUrl+"&"+theParam+"="+theValue
   } else {
     return theUrl+"?"+theParam+"="+theValue
   }
}

alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'name', 'fred'));
alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'phone', '67890'));
alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'email', 'test@server.com'));
alert(replaceQueryStringPart('http://localhost/test.asp', 'email', 'test@server.com'));
</script>


The problem with upper RegExp is that it has to be expressed as string and that is additionaly confusing because of doubled back slashes.
The basic expression is this:  
 String.replace(/\&?parm\=[^\&]+/, "")

And that expression matches this:
   \&?   : zero or one & character
   param\=    : matches that string "param="
  [^\&]+   : matches all characters until the next & character.

So the matched upper characters are replaced by empty string (they are removed from the URL)
The additional String.replace("?@", "?")  does only a paramter shift is the removed paramter was the first parameter (Uhps now I see next problem and will be back in a second...)




0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 63

Accepted Solution

by:
Zvonko earned 250 total points
ID: 11713439
Ok, I got it.
This is more robust:
<script>
function replaceQueryStringPart(theUrl, theParam, theValue){
   theUrl = theUrl.replace(new RegExp("([\\?\\&]"+theParam+"\\=)[^\\&]+","i"),"$1"+theValue);
   if(theUrl.indexOf("?")<0) return theUrl+"?"+theParam+"="+theValue
   if(theUrl.indexOf(theParam+"=")<0) return theUrl+"&"+theParam+"="+theValue
   return theUrl;
}

alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'name', 'fred'));
alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'phone', '67890'));
alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345', 'email', 'test@server.com'));
alert(replaceQueryStringPart('http://localhost/test.asp?email=some@server.com', 'email', 'test@server.com'));
alert(replaceQueryStringPart('http://localhost/test.asp', 'email', 'test@server.com'));
</script>

The additional $1 parameter in the replacing string is the matching content from the first braces match group.

0
 
LVL 1

Author Comment

by:wwarby
ID: 11713560
Thanks very much ;-)

Your last one seems to work fine, although I think I may have cracked it myself from your first reply - here's my solution:

<script>
    function replaceQueryStringPart(theUrl, theParam, theValue){
        if (theUrl.indexOf('?' + theParam)>-1) {
            theUrl = theUrl.replace(new RegExp('\\??'+theParam+'\\=[^\\&]+','gi'),'?'+theParam+'='+theValue);
        } else if (theUrl.indexOf('&' + theParam)>-1) {
            theUrl = theUrl.replace(new RegExp('\\&?'+theParam+'\\=[^\\&]+','gi'),'&'+theParam+'='+theValue);
        } else {
            if (theUrl.indexOf("?")>-1) {
                return theUrl+"&"+theParam+"="+theValue
            } else {
                return theUrl+"?"+theParam+"="+theValue
            }
        }
        return theUrl
    }

alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345&email=test@server.com', 'name', 'fred'));
alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345&email=test@server.com', 'phone', '67890'));
alert(replaceQueryStringPart('http://localhost/test.asp?name=brian&phone=12345&email=test@server.com', 'email', 'foo@bar.com'));
alert(replaceQueryStringPart('http://localhost/test.asp', 'fax', '34567'));
</script>

Certainly couldn't have done it without your example ;-)

-William
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 11713588
Thanks for points.
And you are right, go for your solution. That is the only real way!

See you,
Zvonko

0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Adding Row and Cell on a table 14 25
suddenly angular cli doesn't work. 5 39
Insert Button on a table 16 37
ASP.NET Content Page 3 27
This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question