regex parsing a dynamic parameter from url string - javascript

I have a URL as follows: www.mysite.com?paramNamePrefixXXX=value
What is the best way to parse the url for the parameter name / value where XXX is dynamic/unknown..
Since I don't know the parameter name at render time.. I'd like to match on the 'startswith.. 'paramNamePrefix' + XXX (where XXX is some string..) and return the value
jquery offer a simple way to do this?

var url = "http://www.mysite.com?foo=bar&paramNamePrefixXXX=value&fizz=buzz",
prefix = "paramNamePrefix";
var desiredValue = url.match(new RegExp('[?&]' + prefix + '.*?=(.*?)[&#$]', ''));
desiredValue = desiredValue && desiredValue[1];
console.log(desiredValue); // -> "value"
Demo

This will parse it I believe. The only issue you would run into with the way it's written is if there was an = sign in your parameter value somehow.
((?<=&|\?).+?)(?<=\=)(.+?(?=&|$))
basically I've got it in 2 reference groups
((?<=&|\?).+?) <-- captures parameter name using a look behind
(?<=\=)
(.+?(?=&|$)) <-- captures parameter value using a look ahead

Related

How do I replace characters using Javascript in HTML file?

For example I have a string getting from current URL using javascript
hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc
How do I replace character in the end OrderDateAsc ? If I want to replace for example , OrderDateDesc , how should I do it using Javascript ? The URL infront might be differs all the time , they keyword should be &sortBy.
Please help ,thanks.
var currentUrl = window.location.href;
var url = new URL(currentUrl);
var c = url.searchParams.get("sortBy");
You can get sortBy value like this, and maybe you can use some if statements for if set or not , and you can set like this:
url.searchParams.set('sortBy',"WhateverYouWant");
Also,convert url to string, you can read parameters url.searchParams.get("sortBy"); and again some if statements,
if change :
url = url.Replace(sortByValue,"WhateverYouWant");
this will works too.
But if your string looks like that and you try to change search value, then you will change every "search" value and its not work. :
hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc
change search as WhateverYouWant
hostname/report/WhateverYouWantDate?WhateverYouWantOrderID=&WhateverYouWantDateFrom=2018-10-16&WhateverYouWantDateTo=2018-10-23&WhateverYouWant=WhateverYouWant&sortBy=OrderDateAsc
You see, its bad :)
You could do it with the following code.
//your string
let str = "hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc";
//find "OrderDateAsc" and replace it with "OrderDateDesc"
str = str.replace("OrderDateAsc", "OrderDateDesc" );
you can use regular expression and replace the sortBy param value like that:
const url ='hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc';
const regex = /(&sortBy=OrderDate)(Asc)/gi;
const newUrl = url.replace(regex, '$1Desc');

Javascript get query string parameter values that has query string parameter in turn

I am pretty poor in regex so hoping to get some help here.
I have an url which has a query string parameters. The parameter in turn is a url which has qs parameters of itself.
For eg: my url is something like
http://myurl.com/somepage?ref=/en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true
Now when i use any of the functions to extract the whole query string parameter, i somehow get only the first one.
What i am expecting is: : /en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true
But what i get is: /en-us/products-overview/find-product/home/kitchen/2980?source=google
notice that the other two parameters (isadvertisement and organic) are missing.
my function is
function getUrlParameter(name) {
var url = 'http://myurl.com/somepage?ref=/en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true';
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(url);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
JsFiddle here:
i tried other links from SO to extract QS parameters. none of them seem to handle this scenario
The ampersands in your url are being treated as top level parameter separators. If they are part of a parameter themselves, they need to be escaped. Your escaped url would look like http://myurl.com/somepage?ref=%2Fen-us%2Fproducts-overview%2Ffind-product%2Fhome%2Fkitchen%2F2980%3Fsource%3Dgoogle%26isadvertisement%3Dfalse%26organic%3Dtrue. How you encode the url depends on where it is coming from. JS provides the encodeURIComponent() function.
Then you could use decodeURIComponent() to decode that back to the expected url. The issue is coming from having nested query parameters.
To get query parameters in general though, a built in solution using URL could be something like:
var url=new URL('...');
for (var e of url.searchParams.entries()){
console.log(e);
}

Using Jquery to get numeric value which is in between "/" in link

I am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])

how to replace part of part of string in javascript

I have two GUIDs. I am looking for to replace c013d94e from 1st guid with cd11d94e of second guid in Javascipt.
I checked javascript replace() method but not sure how i can use it with my specific case.
c013d94e-3210-e511-82ec-303a64efb676 - 1st Guid
cd11d94e-3210-e511-82ec-303a64efb676 - 2nd Guid
Following is my code where i am trying to do it
for(var i=0; i < response[1].length;i++)
angular.forEach($scope.studentPermissions[i][0].Children, function (subject) {
string 1stGuid= response[1].data[i].Id; // it contains cd11d94e-3210-e511-82ec-303a64efb676
subject.Id = // it contains c013d94e-3210-e511-82ec-303a64efb676
});
replace takes 2 parameters, the first is the string to search for and the second is the replacement string. It doesn't modify the original string, it simply returns a new string with the value replaced.
You can perform your replace like this:
var guid = 'c013d94e-3210-e511-82ec-303a64efb676';
guid = guid.replace('c013d94e', 'cd11d94e');
console.log(guid); // 'cd11d94e-3210-e511-82ec-303a64efb676'
#Jamen. Yes the other part of 1st string will always be same. How can i use concatenate?
You don't even need to use replace then? Just make a brand new string:
var guid = "cd11d94e-3210-e511-82ec-303a64efb676";
But, to actually answer the question in the title:
var input = "c013d94e-3210-e511-82ec-303a64efb676";
var output = input.replace("c013d94e", "cd11d94e");
console.log(output); // cd11d94e-3210-e511-82ec-303a64efb676
But like I said, in your situation this shouldn't be necessary, based on the quote.

Encoding URL (including characters like &) using jquery or native javascript function?

I have one one hidden paramter in form whose value is
custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
I want to encode it before sending it and so that characters like & can be replaced with %26 etch
i tried using javascript built-in encodeURI("urlToencode") but does not encode characters like &?
Try this code line,
encodeURIComponent("fisrtName=scott&lastName=Miles");
Use https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
You need to call that on each dynamic part (name and value) of the URL query string. So the question is what is the URI component in custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles That doesn't really look like a URL because you have the = before the ?
The most sense that I can make is that the full URL is something like
http://myserver/file.do?custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
In which case, you should build your URL like
var custAddress = "CustomerAddress.do?fisrtName=scott&lastName=Miles";
var initialPath= "/path/to/file.do?";
var url = initialPath + "custAddress=" + encodeURIComponent(custAddress);
Since you mentioned jQuery, you can use a $.param, looks cleaner and does the encoding for you, and you can give it multiple query parameters at once
var url = initialPath + $.param({
custAdrress: custAddress,
otherParam: "paramVal",
// Both the param name and value need to be encoded and $.param does that for you
"funny Name & Param": "funny & value ="
});

Categories