Created
          November 13, 2009 16:57 
        
      - 
      
 - 
        
Save joshcutler/233979 to your computer and use it in GitHub Desktop.  
    Javascript snippet for taking a url and updating query string paramters
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | function add_or_update_query_param(name, value, starter_url) | |
| { | |
| url = starter_url || window.location.href; | |
| query_string_chunks = url.split("?"); | |
| base_url = query_string_chunks[0]; | |
| query_string = (query_string_chunks.length == 2) ? query_string_chunks[1] : null; | |
| chunks = []; | |
| new_value_updated = false; | |
| if (query_string) | |
| { | |
| name_value_pairs = query_string.split("&") | |
| for (var i = 0; i < name_value_pairs.length; i++) | |
| { | |
| pair = name_value_pairs[i].split("="); | |
| if (pair.length == 2) | |
| { | |
| if (pair[0].toLowerCase() === name.toLowerCase()) | |
| { | |
| chunks.push(name + "=" + value); | |
| new_value_updated = true; | |
| } | |
| else | |
| { | |
| chunks.push(pair[0] + "=" + pair[1]); | |
| } | |
| } | |
| } | |
| } | |
| if (!new_value_updated) | |
| { | |
| chunks.push(name + "=" + value); | |
| } | |
| return (base_url + "?" + chunks.join("&")); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment