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 ="
});
Related
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);
}
I'm using javascript function to submit form, and in the javascript function, I'd specify form.action= "Struts2 url goes here";
Here's a snippet of my code:
var form = document.forms['myForm'];
if (form != null) {
var backURL = "ActionB!someMethodB.action?Bparam1=somevalue&Bparam2=somevalue";
form.action="ActionA!someMethodA.action?Aparam1=somevalue&Aparam2=" + backURL;
form.submit();
}
The problem is that in the action method someMethodA, the value for Aparam2 is always cut off by the first ampersand in backURL.
I tried to enclose backURL with quotes like this form.action="ActionA!someMethodA.action?Aparam1=somevalue&Aparam2='" + backURL + "'"; but it did not work. It kind of makes me feel like that the value of backURL is not treated as a whole but parsed as well.
I would like to know if there's a way to work around this.
If you want to use a parameter in the url which contains special characters they should be urlencoded.
var backURL = encodeURIComponent("ActionB!someMethodB.action?Bparam1=somevalue&Bparam2=somevalue");
Also, a hardcoded value for URL could be built on server with s:url tag.
var backURL = encodeURIComponent('<s:url action="ActionB" method="someMethodB"><s:param name="Bparam1" value="somevalue"/><s:param name="Bparam2" value="somevalue"/></s:url>');
In this case by default & is escaped to & but escaped value is used normally with the browser.
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])
I am trying to append multiple parameter value pairs to a url for an ajax request. I know that this is supposed to be done using & instead of &. Why then, does the first function work and the second one fails?
function accountByName(firstName, lastName, resultRegion) {
var baseAddress = "Bank";
var data = "firstName=" + getValue(firstName) + "&lastName=" + getValue(lastName);
var address = baseAddress + "?" + data;
ajaxResult(address, resultRegion);
}
function accountByName(firstName, lastName, resultRegion) {
var baseAddress = "Bank";
var data = "firstName=" + getValue(firstName) + "&lastName=" + getValue(lastName);
var address = baseAddress + "?" + data;
ajaxResult(address, resultRegion);
}
When I do print statements in the serverside java code the firstName variable prints fine, but the lastName variable always comes back null when I use & Both variables print fine when I just use &, but I know this is not correct XML.
So here's what your instructor meant:
In an (X)HTML page if you have something like:
Link
You should use (even though it really doesn't make a difference except to the validator)
Link
That is the ONLY time you should use an & in a query string.
You are incorrect: you are not supposed to use & as the parameter separator in a URL. The first function constructs the URL:
Bank?firstName=foo&lastName=bar
The second:
Bank?firstName=foo&lastName=bar
The 1st URL has two parameters: firstName and lastName with the values foo and bar.
The 2nd URL has two parameters: firstName and amp;lastName with the values foo and bar. (Note: I believe the second parameter name is invalid and am not sure how it'd be parsed in Java; it may be library/server dependent)
Your Java code fails printing the lastName parameter in the second case because in that case it is not set.
Your confusion seems to stem from a misunderstanding of the URL format. The URL format is unrelated to XML or HTML. It is completely separate from the two. & is an XML/HTML entity. Were the URL some form of XML, you would be correct. However, as it is not one should not expect it to follow the rules and standards of XML.
You're creating a URL, not some XML content. You have to think about what system is going to be paying attention. An XML/HTML parser is never going to look at that URL you're creating. The server, however, will certainly be interested in interpreting the URL as a URL. The XML entity syntax & is completely alien to something parsing a URL.
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¶mNamePrefixXXX=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