I'm trying to write a function that will remove a query argument from a url in javascript. I think I have it using regex, but I'm not sure if I've missed anything. Also, I can't shake the feeling that there was probably a better way to do this that didn't involve me messing around with regex half the day and running the risk of later finding out that I didn't take some kind of corner case into account.
remove_query_argument = function(url, arg){
var query_arg_regex;
// Remove occurences that come after '&' symbols and not the first one after the '?'
query_arg_regex = new RegExp('&' + arg + '=[^(?:&|$)]*', 'ig');
url = url.replace(query_arg_regex, '');
// remove the instance that the argument to remove is the first one
query_arg_regex = new RegExp('[?]' + arg + '[^(?:&|$)]*(&?)', 'i');
url = url.replace(query_arg_regex, function (match, capture) {
if( capture != '&' ){
return '';
}else{
return '?'
}
});
return url;
}
Does anyone see any problems with this code or would like to suggest a better implementation or way of going about this?
Thanks!
If you have a lot of URL-related operations, you better try this awesome js library https://github.com/medialize/URI.js
Given a percent-encoded URL, the following function will remove field-value pairs from its query string:
var removeQueryFields = function (url) {
var fields = [].slice.call(arguments, 1).join('|'),
parts = url.split( new RegExp('[&?](' + fields + ')=[^&]*') ),
length = parts.length - 1;
return parts[0] + '?' + (length ? parts[length].slice(1) : '');
}
Some examples:
var string = 'http://server/path/program?f1=v1&f2=v2';
removeQueryFields( string, 'f1' ); // 'http://server/path/program?f2=v2'
removeQueryFields( string, 'f2' ); // 'http://server/path/program?f1=v1'
removeQueryFields( string, 'f1', 'f2' ); // 'http://server/path/program'
Related
I have this URL
https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request
Here I am getting sys_id two times with different parameters. So I need to remove the second & sign and all text after that.
I tried this
location.href.split('&')[2]
I am sure it doesn't work. Can anyone provide some better solution?
Firstly, you should split the string into an array then use slice to set the starting index number of the element which is 2 in your case and then join the array again into the string.
Read more about these methods JavaScript String split() Method, jQuery slice() Method and JavaScript Array join() Method
var url = 'https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
url = url.split("&").slice(0,2).join("&");
console.log(url);
Maybe like this:
var url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
var first=url.indexOf('&');
var second=url.indexOf('&',first+1);
var new_url=url.substring(0,second);
console.log(new_url);
You need to find the 2nd occurrence of &sys_id. From there onwards remove all text.
Below is working code:
let url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
let str1=url.indexOf('&sys_id');
let str2=url.indexOf('&sys_id',str1+1);
console.log(url.substring(0,str2));
This is a bit more verbose, but it handles all duplicate query params regardless of their position in the URL.
function removeDuplicateQueryParams(url) {
var params = {};
var parsedParams = '';
var hash = url.split('#'); // account for hashes
var parts = hash[0].split('?');
var origin = parts[0];
var retURL;
// iterate over all query params
parts[1].split('&').forEach(function(param){
// Since Objects can only have one key of the same name, this will inherently
// filter out duplicates and keep only the latest value.
// The key is param[0] and value is param[1].
param = param.split('=');
params[param[0]] = param[1];
});
Object.keys(params).forEach(function(key, ndx){
parsedParams += (ndx === 0)
? '?' + key +'='+ params[key]
: '&' + key +'='+ params[key];
});
return origin + parsedParams + (hash[1] ? '#'+hash[1] : '');
}
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff') );
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff#withHash') );
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
url = url.slice(0, url.indexOf('&', url.indexOf('&') + 1));
console.log(url);
Try this :)
Try this:
var yourUrl = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
var indexOfFirstAmpersand = yourUrl.search("&"); //find index of first &
var indexOfSecondAmpersand = indexOfFirstAmpersand + yourUrl.substring((indexOfFirstAmpersand + 1)).search("&") + 1; //get index of second &
var fixedUrl = yourUrl.substring(0, indexOfSecondAmpersand)
$(".answer").text(fixedUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="answer">
</p>
You can manipulate the url using String.prototype.substring method. In the example below I created a function that takes a url string and checks for a duplicate parameter - it returns a new string with the second occurrence removed.
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request";
function stripDuplicateUrlParameter(url, parameterName) {
//get the start index of the repeat occurrance
var repeatIdx = url.lastIndexOf('sys_id');
var prefix = url.substring(0, repeatIdx);
var suffix = url.substring(repeatIdx);
//remove the duplicate part from the string
suffix = suffix.substring(suffix.indexOf('&') + 1);
return prefix + suffix;
}
console.log(stripDuplicateUrlParameter(url));
This solves your specific problem, but wouldn't work if the parameter occurred more than twice or if the second occurrence of the string wasn't immediately following the first - you would probably write something more sophisticated.
As someone already asked - why is the url parameter being duplicated in the string anyway? Is there some way to fix that? (because the question asked seems to me to be a band-aid solution with this being the root issue).
I find it hard to believe this hasn't been asked but I can find no references anywhere. I need to add a URI hash fragment and update the value if it already is in the hash. I can currently get it to add the hash but my regex doesn't appear to catch if it exists so it adds another instead of updating.
setQueryString : function() {
var value = currentPage;
var uri = window.location.hash;
var key = "page";
var re = new RegExp("([#&])" + key + "=.*#(&|$)", "i");
var separator = uri.indexOf('#') !== -1 ? "&" : "#";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
},
Also if this can be made any cleaner while preserving other url values/hashes that would be great.
example input as requested
Starting uri value:
www.example.com#page=1 (or no #page at all)
then on click of "next page" setQueryString gets called so the values would equal:
var value = 2;
var uri = '#page1'
var key = 'page'
So the hopeful output would be '#page2'.
As to your regex question, testing if the pattern #page=(number) or &page=(number) is present combined with capturing the number, can be done with the regex /[#&]page\=(\d*)/ and the .match(regex) method. Note that = needs escaping in regexes.
If the pattern exists in the string, result will contain an array with the integer (as a string) at result[1]. If the pattern does not exist, result will be null.
//match #page=(integer) or &page=(integer)
var test = "#foo=bar&page=1";
var regex = /[#&]page\=(\d*)/;
var result = test.match(regex);
console.log(result);
If you want to dynamically set the key= to something other than "page", you could build the regex dynamically, like the following (note that backslashes needs escaping in strings, making the code a bit more convoluted):
//dynamically created regex
var test = "#foo=bar&page=1";
var key = "page"
var regex = new RegExp("[#&]" + key + "\\=(\\d*)");
var result = test.match(regex);
console.log(result);
I am taking first steps with regular expressions. I am trying to increment the last digit in a url string but for some reason I cant figure out I increment other digits.
Example
string: http://example.com/18-something-something/6
should become: http://example.com/18-something-something/7
in practice: http://example.com/19-something-something/7
As you can see, 18 turned to 19 which is what im trying to avoid.
This is my JS:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
jQuery(document).ready(function() {
url = window.location.href;
var newrl = url.replace(/(\d+)+/g, function(match, number) {
return parseInt(number) + 1;
});
var m = url.match(/\/([^\/]+)[\/]?$/);
link = jQuery('a[class=nextpostslink]').attr('href');
if (!isNumeric(m[1])) {
jQuery('.post-content').find('img:first').wrap(jQuery("<div class='slideshow-wrapper'><a href=2>").attr("href", link));
jQuery('.post-content').find('img:first').after('<div id="start-slideshow"><img src="chevron.png"></div>');
} else {
jQuery('.post-content').find('img:first').wrap(jQuery("<div class='slideshow-wrapper'><a href=" + newrl + ">").attr("href", link));
}
});
Any idea what am I missing? thx
You don't want to have a global match (g), but removing that flag alone won't help.
If you want match with and without query parameter, then you need to make sure that it is either at the end of the string $ or right before the query parameters ? so your RegExp has to look like this:
var url = 'http://example.com/18-something-something/6?param=34';
var newrl = url.replace(/(\d+)($|\?)/, function(match, number, questionmark) {
return String(++number) + questionmark;
});
console.log(newrl);
You should use /(\d+)$/ as a regex to increment only the last digit.
I would not do this with regular expressions, truthfully.
I'd do something like:
var url = "http://example.com/18-something-something/6";
function advanceUrl(url) {
// Split the URL into chunks
var chunks = url.split("/");
// Get the last segment of the URL
var lastPage = chunks.pop();
// Increment it
lastPage++;
// And put it back
chunks.push(lastPage);
// Re-create the URL
var newUrl = chunks.join("/");
// Log it
console.log(newUrl);
// Return it.
return newUrl;
}
advanceUrl(url);
I have a URL say
dummy URL
http://www.google.com/?v=as12&&src=test&img=test
Now I want to remove the &src=test& part alone.I know we can use indexof but somehow I could not get the idea of getting the next ampersand(&) and removing that part alone.
Any help.The new URL should look like
http://www.google.com/?v=as12&img=test
What about using this?:
http://jsfiddle.net/RMaNd/8/
var mystring = "http://www.google.com/?v=as12&&src=test&img=test";
mystring = mystring.replace(/&src=.+&/, ""); // Didn't realize it isn't necessary to escape "&"
alert(mystring);
This assumes that "any" character will come after the "=" and before the next "&", but you can always change the . to a character set if you know what it could be - using [ ]
This also assumes that there will be at least 1 character after the "=" but before the "&" - because of the +. But you can change that to * if you think the string could be "src=&img=test"
UPDATE:
Using split might be the correct choice for this problem, but only if the position of src=whatever is still after "&&" but unknown...for example, if it were "&&img=test&src=test". So as long as the "&&" is always there to separate the static part from the part you want to update, you can use something like this:
http://jsfiddle.net/Y7LdG/
var mystring1 = "http://www.google.com/?v=as12&&src=test&img=test";
var mystring2 = "http://www.google.com/?v=as12&&img=test&src=test";
var final1 = removeSrcPair(mystring1);
alert(final1);
var final2 = removeSrcPair(mystring2);
alert(final2);
function replaceSrc(str) {
return str.replace(/src=.*/g, "");
}
function removeSrcPair(orig) {
var the_split = orig.split("&&");
var split_second = the_split[1].split("&");
for (var i = split_second.length-1; i >= 0; i--) {
split_second[i] = replaceSrc(split_second[i]);
if (split_second[i] === "") {
split_second.splice(i, 1);
}
}
var joined = split_second.join("&");
return the_split[0] + "&" + joined;
}
This still assumes a few things - the main split is "&&"...the key is "src", then comes "=", then 0 or more characters...and of course, the key/value pairs are separated by "&". If your problem isn't this broad, then my first answer seems fine. If "src=test" won't always come first after "&&", you'd need to use a more "complex" Regex or this split method.
Something like:
url = "http://www.google.com/?v=as12&&src=test&img=test"
firstPart = url.split('&&')[0];
lastPart = url.split('&&')[1];
lastPart = lastPart.split('&')[1];
newUrl = firstPart+'&'+lastPart;
document.write(newUrl);
Details: Use the split method.
Solution Edited: I changed the below to test that the last query string exists
var url = "http://www.google.com/?v=as12&&src=test&img=test";
var newUrl;
var splitString = url.split('&');
if (splitString.length > 3)
{
newURL = splitString[0] + "&" + splitString[3];
}
else
{
newURL = splitString[0];
}
So I am wanting to replace GET variable values in a url and if the variable does not exist, then add it to the url.
EDIT: I am doing this to a elements href not the pages current location..
I am not good with javascript but I do know how to use jQuery quite well and the basics of javascript. I do know how to write regex but not how to use the javascript syntax of regex and what functions to use it with.
Here is what I have so far and it does have an error on line 3: See it on jsfiddle(or below): http://jsfiddle.net/MadLittleMods/C93mD/
function addParameter(url, param, value) {
var pattern = new RegExp(param + '=(.*?);', 'gi');
return url.replace(pattern, param + '=' + value + ';');
alert(url);
}
No need to use jQuery on this one. Regular Expressions and string functions are sufficient. See my commented code below:
function addParameter(url, param, value) {
// Using a positive lookahead (?=\=) to find the
// given parameter, preceded by a ? or &, and followed
// by a = with a value after than (using a non-greedy selector)
// and then followed by a & or the end of the string
var val = new RegExp('(\\?|\\&)' + param + '=.*?(?=(&|$))'),
parts = url.toString().split('#'),
url = parts[0],
hash = parts[1]
qstring = /\?.+$/,
newURL = url;
// Check if the parameter exists
if (val.test(url))
{
// if it does, replace it, using the captured group
// to determine & or ? at the beginning
newURL = url.replace(val, '$1' + param + '=' + value);
}
else if (qstring.test(url))
{
// otherwise, if there is a query string at all
// add the param to the end of it
newURL = url + '&' + param + '=' + value;
}
else
{
// if there's no query string, add one
newURL = url + '?' + param + '=' + value;
}
if (hash)
{
newURL += '#' + hash;
}
return newURL;
}
And here is the Fiddle
Update:
The code now handles the case where there is a hash on the URL.
Edit
Missed a case! The code now checks to see if there is a query string at all.
I would go with this small but complete library to handle urls in js:
https://github.com/Mikhus/jsurl
See Change URL parameters. It answers your question in a more general manner (changing any url parameter). There are solutions for both jQuery and regular js in the answers section.
It also looks like url.replace should be location.replace but I may be wrong (that statement's based on a quick google search for 'url.replace javascript').
<script type="text/javascript">
$(document).ready(function () {
$('input.letter').click(function () {
//0- prepare values
var qsTargeted = 'letter=' + this.value; //"letter=A";
var windowUrl = '';
var qskey = qsTargeted.split('=')[0];
var qsvalue = qsTargeted.split('=')[1];
//1- get row url
var originalURL = window.location.href;
//2- get query string part, and url
if (originalURL.split('?').length > 1) //qs is exists
{
windowUrl = originalURL.split('?')[0];
var qs = originalURL.split('?')[1];
//3- get list of query strings
var qsArray = qs.split('&');
var flag = false;
//4- try to find query string key
for (var i = 0; i < qsArray.length; i++) {
if (qsArray[i].split('=').length > 0) {
if (qskey == qsArray[i].split('=')[0]) {
//exists key
qsArray[i] = qskey + '=' + qsvalue;
flag = true;
break;
}
}
}
if (!flag)// //5- if exists modify,else add
{
qsArray.push(qsTargeted);
}
var finalQs = qsArray.join('&');
//6- prepare final url
window.location = windowUrl + '?' + finalQs;
}
else {
//6- prepare final url
//add query string
window.location = originalURL + '?' + qsTargeted;
}
})
});
</script>