I'm new to regex and I'm using it in jquery to remove/replace the url but when i triggered an anchortag with href="#" the url will add a # and I'm not able to replace it with my current regex fix to replace the url.
http://localhost:3131/Main/MainPage?a=1221#&ab=&ac=
the original link onload is
http://localhost:3131/Main/MainPage?a=1221
but after triggering an anchortag with href="#" return, it becomes this:
http://localhost:3131/Main/MainPage?a=1221#
and my expected result upon removing the hash(#) in my url is this:
http://localhost:3131/Main/MainPage?a=1221&ab=&ac=
heres my function for replacing the url when closing modal windows in jquery
function updateQueryStringParameter(uri, key, value, key1,value1) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)" + key1 + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2' + key1 + "=" + value1 + '$3' );
}
else {
return uri + separator + key + "=" + value + separator + key1 + "=" + value1;
}
};
Hope someone can help me as i am a beginner on using Regular expression specially in jquery.
Thanks!
Related
The following function is designed to replace a variable in the URL.
It works, but I want to make it so that if you pass in a variable that doesn't exist in the URL, it will add it to the URL.
window.setUrlParameter = function(param, value) {
const regExp = new RegExp(param + "(.+?)(&|$)", "g");
const newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
window.history.pushState("", "", newUrl);
}
There is the function. It takes the param name that you want to replace, and the value you want to set.
As I stated earlier, I want it to be able to not only replace variables, but set them as well.
Thanks!
This function should also be faster than using a regex, modified from this answer.
(The arrow function is just ES6 syntax, you can use normal functions if you want too)
window.setUrlParameter = (param, value) => {
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(param + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(param));
var suffix = url.substring(url.indexOf(param));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + param + "=" + value + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + param + "=" + value;
else
url += "&" + param + "=" + value;
}
window.history.pushState(null, null, url + hash);
}
You have the regex, you can just test the url for the same thing, and add it if it isn't there
window.setUrlParameter = function(param, value) {
const regex = new RegExp(param + "(.+?)(&|$)", "g");
const exist = regex.test(window.location.href);
let addQS = window.location.search.length > 0 : '&' : '?';
let newUrl;
if (exist) {
newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
} else {
newUrl = window.location.href + addQS + param + "=" + value;
}
window.history.pushState("", "", newUrl);
}
I'd highly recommend cleaning this up with RegEx, but you could just check whether or not the href includes the parameter
window.setUrlParameter = function(param, value) {
const regExp = new RegExp(param + "(.+?)(&|$)", "g");
let newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
if (! window.location.href.includes(param) )
newUrl+='&'+param+'='+value
window.history.pushState("", "", newUrl);
}
Nobody here used the URLSearchParams API, so I thought I'd show you that way:
function modifyLocation( param, value )
{
var qParams = window.location.search.split('?')[0];
var urlParams = new URLSearchParams(qParams);
if( urlParams.has(param) ){
urlParams.delete(param);
}
urlParams.append(param, value);
return window.location.href.split('?')[0] + '?' + urlParams.toString();
}
// To test on CodePen, I used editors = 4, because CodePen has that param
var newUrl = modifyLocation('editors','4');
console.log(newUrl);
// window.history.pushState("", "", newUrl);
I wrote a javascript function that you can use to add parameters to your current URL. It returns your current URL with added parameters. I am not sure if this function will work on all browsers. Currently it works in my Chrome browser perfectly. Can you please tell me disadvantages of this function or how can I improve it or any other way to do the same thing?
function AddParamToURL(param_key, param_value)
{
var currentURL, flag, newURL;
currentURL = window.location.href;
flag = currentURL.indexOf("?");
if (flag == -1)
{
newURL = currentURL + "?" + param_key + "=" + param_value;
}
else
{
newURL = currentURL + param_key + "=" + param_value;
}
return newURL;
}
I would send the path as a parameter to the function, because you won't always be just using the current window.href, you might want to send some other path as well.
You can then remove some redundancy by dealing with the param separator before adding to the path.
And this will work in a loop when you have more than one parameter to add.
function AddParamToURL(currentPath, param_key, param_value)
{
var flag = currentPath.split("?");
var paramSeparator = (flag.length <= 1) ? "?" : "&";
return currentPath + paramSeparator + param_key + "=" + param_value;
}
Fixed the case where there could be a ? without any key after it and added & in second case
Fiddle : http://jsfiddle.net/0spsjeaL/3/
function AddParamToURL(param_key, param_value)
{
var currentURL, flag, newURL;
currentURL = window.location.href;
flag = currentURL.split("?");
if(flag.length <= 1)
{
newURL = currentURL + "?" + param_key + "=" + param_value;
}
else
{
newURL = currentURL + "&" + param_key + "=" + param_value;
}
return newURL;
}
alert(AddParamToURL('name', 'John'));
You can inline a lot of stuff and param_key + "=" + param_value is duplicate code. Also you are forgetting & between parameters.
function AddParamToURL(param_key, param_value)
{
var url = window.location.href;
var newUrl = url.indexOf('?') < 0 ? url + '?' : url + '&';
return newUrl + param_key + '=' param_value;
}
I got this function from here in stack to replace url parameters like that :
function replaceUrlParam(paramName, paramValue){
var currentUrl = window.location.href;
var pattern = new RegExp('('+paramName+'=).*?(&|$)')
var newUrl = currentUrl.replace(pattern,'$1' + paramValue + '$2');
if(newUrl == currentUrl){
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
window.history.pushState('',document.title,newUrl);
return newUrl;
}
www.mysite.com/index.php?id=14&&cat=20
and i use it like that:
replaceUrlParam('id', 15);
like that works fine.
But the problem is it duplicates the id if i use same id which is in the url like that.
replaceUrlParam('id', 14)--will give--->www.mysite.com/index.php?id=14&&cat=20&&id=14
How can i change this function to not give duplicates when its same id ?
Thanks
fiddle here
The if statement in the function explains everything. If the url hasn't changed then it tacks the param/value onto the end. Sounds like you want to also check that the value isn't already in there, like:
if(newUrl == currentUrl && newUrl.indexOf(paramName+'='+paramValue) === -1) {
//...
}
Here's an updated jsfiddle
www.mysite.com/index.php?id=14&&cat=20
and
replaceUrlParam('id', 14)
is trying to repalce id:14 with id:14. So in this case: newUrl == currentUrl will resolve to true.
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
will find the index of the '?', which is 24, which is > 0.
So in the end you're doing this:
newUrl = www.mysite.com/index.php?id=15&&cat=20 + paramName + '=' + paramValue
In either scenario, if your (currentUrl == newUrl) == true your concatanation will end up either doing
newUrl = newUrl + '&' + paramName + '=' + paramValue
or
newUrl = newUrl + '?' + paramName + '=' + paramValue
Either way will duplicate your value at the end.
the website i maintain is moving from the standard php url format:
http://example.com/page.php?key=value&key=value...
to a more seo friendly format like this:
http://example.com/page/key/value/key/value...
I was using this function in javascript to add, update/modify the old formatted url string:
function UpdateQueryString(key, value, url) {
if (!url) url = window.location.href;
var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi");
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null)
return url.replace(re, '$1' + key + "=" + value + '$2$3');
else {
return url.replace(re, '$1$3').replace(/(&|\?)$/, '');
}
}
else {
if (typeof value !== 'undefined' && value !== null) {
var separator = url.indexOf('?') !== -1 ? '&' : '?',
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (hash[1]) url += '#' + hash[1];
return url;
}
else
return url;
}
}
This worked perfectly. Now this function highlights the two things im bad at, javascript and regexs. I am trying to modify this function to use slashes, '/' instead of ?&=. This is my first try at it:
function myUpdateQueryString(key, value, url)
{
if (!url) url = window.location.href;
var re = new RegExp("([/])" + key + "(/)(.*)", "gi");
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null)
return url.replace(re, '$1' + key + "/" + value + '$2$3');
else {
return url.replace(re, '$1$3').replace(/(\/)$/, '');
}
}
else {
if (typeof value !== 'undefined' && value !== null) {
var separator = '/',
hash = url.split('#');
url = hash[0] + separator + key + '/' + value;
if (hash[1]) url += '#' + hash[1];
return url;
}
else
return url;
}
}
This function is getting me very close. It will add new key/values to the url string, but i am having trouble updating/modifying current values in the string.
I think its an easy fix. I am just having trouble wrapping my head around $2$3 in the regex and a few other things.
Thanks
I think i have found the answer
This seems to be working for now:
function UpdateQueryString(key, value, url)
{
if (!url) url = window.location.href;
var re = new RegExp("([/])" + key + "/.*?(/|$)", "gi");
var separator = '/';
if (url.match(re)) {
return url.replace(re, '$1' + key + "/" + value + '$2');
}
else {
return url + separator + key + "/" + value;
}
}
Can anyone see anything wrong with this?
Could you do something like this instead?
url.split('/?|&|=/').join('/');
This should replace all question marks, ampersands, and equal signs in your URL with slashes.
function UpdateQueryString(key, value, url)
{
if (!url) url = window.location.href;
var re = new RegExp("([/])" + key + "/.*?(/|$)", "gi");
var separator = '/';
if (url.match(re)) {
return url.replace(re, '$1' + key + "/" + value + '$2');
}
else {
return url + separator + key + "/" + value;
}
}
This seems to work. Can anyone find anything wrong with this. I am not very good at regexs or javascript
I am trying to have 2 variable values passed in a url, which url will be redirected after. How can I insert them in a JavaScript string?
I have:
var a = document.getElementById("username_a").value;
var b = document.getElementById("username_b").value;
and want something like: var string_url = "http://www.example.com/?{a}blabla={b}" and then redirect somehow.
In PHP I would go with that code for example: <iframe src="http://www.example.com?query=<?php echo $the_variable;?>">
You can add strings in JavaScript, "a" + "b" == "ab" evaluates to true.
So what you want is probably var string_url = "http://www.example.com/?" + a + "&blabla=" + b;
But you should ever escape vars especially if they come from inputs, so try
a = encodeURIComponent(a);
b = encodeURIComponent(b);
And then
var string_url = "http://www.example.com/?" + a + "&blabla=" + b;
To redirect you can use window.location:
window.location = string_url;
use the ampersand to split vars
var string_url = "http://www.example.com/?" + "username_a=" + a + "&username_b=" + `b
Could be made more sopisticated, but that in essence is what you need
JavaScript doesn't do string interpolation. You have to concatenate the values.
var uri = "http://example.com/?" + encodeUriComponent(name_of_first_variable) + "=" + encodeUriComponent(value_of_first_variable) + '&' + encodeUriComponent(name_of_second_variable) + "=" + encodeUriComponent(value_of_second_variable);
location.href = uri;