Parsing Friendly Urls in Javascript - javascript

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

Related

How to update internal links parameters based on current URL using jQuery?

How we can update the internal links of the page if some visits from specific URL.
For Example.
Some Users comes from Facebook and URL is
https://www.example.com/?utm_source=facebook&utm_medium=cpc&utm_campaign=mobile
and I want to update all my particular links to update based on URL, In case of facebook
Original URL
https://www.example.com/cat/i?pid=ABCD&affid=aff1&affExtParam1=para1&affExtParam2=para2
Updated URL after User visit from facebook link
https://www.example.com/cat/i?pid=ABCD&affid=aff1&affExtParam1=facebook&affExtParam2=mobile
Even If It can edit one parameter in URL that will be helpful.
Note:
In param1 and param2 can be any text in exiting page.
Thanks for the hints. I have tried and able to replace one URL Parameters. Below is the code.
Combined scripts from different answers and use below code.
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
if( value === undefined ) {
if (uri.match(re)) {
return uri.replace(re, '$1$2');
} else {
return uri;
}
} else {
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
var hash = '';
if( uri.indexOf('#') !== -1 ){
hash = uri.replace(/.*#/, '#');
uri = uri.replace(/#.*/, '');
}
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
return uri + separator + key + "=" + value + hash;
}
}
}
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var key = "affExtParam2";
var value = $.urlParam('utm_source');
$('a').each(function(){
var uri = $(this).attr("href");
$(this).attr("href" , updateQueryStringParameter( uri, key, value ));
});
Not able to test in JS fiddle but working correctly in local, if you guys can further optimize that will be great help.

Remove the query string before appending the url parameters

I want to remove the query string from my URL before I add my URL parameters. Say my site is https://www.abcd.com/test I am appending some parameters to my URL like /def?key=value through javascript. But the page is built as https://www.abcd.com/test?/def?key=value. I want it to be https://www.abcd.com/test/def?key=value Below is my code. Any input is greatly appreciated.
redirectURL: function() {
var currentURL = window.location.href;
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
if (currentURL.indexOf("def") == -1){
document.location.search = '/def'+ '?' + 'key' + '=' + 'value';
}else{
document.location.search = '?' + 'key' + '=' + 'value';
}
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
document.location.search = kvp.join('&');
}
}
You are appending your URL parameters to the location.search property which is the querystring:
document.location.search = '/def'+ '?' + 'key' + '=' + 'value';
I believe what you want to do is append your URL parameters to the location.href property, but first you will need to separate the existing search string (querystring) from it:
var urlBase = window.location.href.split('?')[0];
window.location.href = urlBase + '/def'+ '?' + 'key' + '=' + 'value';

Replace parameter in URL - two parameters

I have a simple script for replace prameter:
function replaceQueryParam(param, newval, search) {
//condition over accumulation & in url if I use null
if(newval == null){
ampersand = "";
} else{
ampersand = "&";
}
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
return (query.length > 2 ? query + ampersand : "?") + (newval ? param + "=" + newval : '');
}
And I use it:
var str = window.location.search
str = replaceQueryParam('myParam', 'myValue', str)
window.location = window.location.pathname + str
It run perfect, but I want use the function edit to parameters with only one redirect. If I have it in onClick event, I cant use:
var str = window.location.search
str = replaceQueryParam('myParam', 'myValue', str)
window.location = window.location.pathname + str
var str = window.location.search
str = replaceQueryParam('SecondParam', 'null', str)
window.location = window.location.pathname + str
The second parameter I want null (I want delete second parameter from url) - if it by simple.
Thanks and sorry for my English
PS: It can by in jquery
All of my event:
$("#typ span").click(function() {
var url = window.location.href;
//if it exist
if (url.indexOf('typ') > -1){
var str = window.location.search
str = replaceQueryParam('typ', $(this).attr('id'), str)
window.location = window.location.pathname + str
//if its doesnt exist - add new
} else {
if (url.indexOf('?') > -1){
url += '&typ='+$(this).attr('id');
}else{
url += '?typ='+$(this).attr('id');
}
window.location.href = url;
}
});
if click on span I want do this (add or replace "typ") and null other parameter (if it exist) - with only one redirect.
Take a look at the existing URL interface.
Example:
const url = new URL('http://test.com/products?category=bears&page=3');
url.searchParams.set('category', 'puppies');
console.log(url.href); // Result: http://test.com/products?category=puppies&page=3

How to edit this function and make it set URL parameter if it doesn't exist

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);

Does my simple javascript function, is the best way to add parameters to current URL

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;
}

Categories

Resources