is there a way to exclude certain chars from encodeURIComponent - javascript

i am building a query string for my url and need to exclude certain chars from the encode.
I want to exclude the "&" and the "=" so that I can make a statement as such:
first=blah&second=blah and so on....
I guess the best way to put it is how do I stop them from being encoded?
some code:
else if (array[i].nodeName == "SELECT") {
if (array[i].id == "multiple") {
var selected = $.map($('#multiple option:selected'),
function (e) {
return $(e).val();
});
$.each(selected, function (index, value) {
name = array[i].name;
values += app + "\&" + key + "=";
});
} else {
name = arr[i].name;
values = arr[i].value;
}
}
key = encodeURIComponent(name);
value = encodeURIComponent(values);
queryString += name + "=" + values + "&";

Is there a way to exclude certain chars from encodeURIComponent?
No. It's a builtin function that takes exactly one argument.
You do need to encode & when it appears in the middle of a key or value so the simplest solution is to encode the individual names and values before combining them. Define
function emit(name, value) {
queryString += (queryString.indexOf("?") >= 0 ? "&" : "?")
+ encodeURIComponent(name) + "=" + encodeURIComponent(value);
}
and then call that function for each name/value pair in multiple selects or once for each other checked input.
else if (array[i].nodeName=="SELECT" ){
if(array[i].id == "multiple"){
var selected = $.map( $('#multiple option:selected'),
function(e){return $(e).val();});
$.each(selected, function(index, value){
emit(array[i].name, value);
});
} else {
emit(arr[i].name, arr[i].value);
}
}
Using encodeURI or similar will not properly encode #, = or other necessary code-points.

The name of the function should suggest how it should be used: call it on the pieces of the query string, not the whole query string.
edit — I've tried to create an example based on your code, but I can't figure out what it's trying to do. As it stands it seems to have syntax errors.

Related

Javascript: Appending second dropdown selection to URL

Hi I have two dropdowns in my webpage. How do I append the second dropdown selection to the URL without using.
window.location.href +="&selected2="+value2;
please tell me what change I must to the the function setsecondparam where value1 is the selection from the first dropdown.
function seturl(sel){
var value = sel.options[sel.selectedIndex].value;
window.location.href = "website.php?selected1="+value;
}
function setsecondparam(sel,value1)
{
var value2 = sel.options[sel.selectedIndex].value;
window.location.href ="website.php?selected1="+value1+"&selected2="+value2;
}
Thanks in advance
It's better to use one function. I wrote it more or less in ES5, you can change it to ES6 if you use babel.
function insertParams (key, value) {
let search = window.location.search;
let regex = new RegExp(key+"=[^\&]*");
search = search.replace(regex, key + '=' + value);
​
if (!regex.test(search)) {
search += (search.length > 0 ? '&' : '?') + key + '=' + value;
}
​
document.location.search = search;
}

Javascript - Incrementing specific numbers of a string

I have a string that looks like this
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
Is there an easier way to increment the numbers at the end of "question1" and "answer0" inside of the string? I have tried to separate the contents of the string using the following method:
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
idArray = id.split('_');
originalArray = idArray.slice();
if (idArray) {
idArray.pop();
for (i = 0; i < 2; i++) {
idArray.shift();
}
}
The above results in:
idArray = ["question1","answer0"];
but the final result needs to be a string, I know I'll probably need to concatenate it later, so I can pass it into another argument. I just need to isolate those two numbers and increment only those two. I was searching for an easier way to finish that task but I haven't come across anything like that. Also jQuery isn't an option for me since I'm trying to accomplish this using just javascript and the console. Thank you for your help in advance.
You can try this :
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
var incrementQuestion = function (id) {
return id.replace(/question([0-9]+)/, function (val1, val2) {
return "question" + (parseInt(val2) + 1)
}) }
var incrementAnswer = function (id) {
return id.replace(/answer([0-9]+)/, function (val1, val2) {
return "answer" + (parseInt(val2) + 1)
}) }
then increment using:
id = incrementAnswer(id);
and
id = incrementQuestion(id);
You can use regular expressions to find the string "question1" and replace it with "question2" - or more accurately "question{any number here}" and replace with "question{any other number}"
var id = 'CourseContent1_activityContent34169_question1_answer0_ac'
var re = /question\d+/
var id2 = id.replace(re,"question2")
You can do the same for answer\d+
You should use replace function of RegExp:
Please run the example below:
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
alert('before:\r' + id)
id = id.replace(/question([0-9]+).*answer([0-9]+)/, function(a, b, c) {
return 'question' + (parseInt(b) + 1) + '_answer' + (parseInt(c) + 1)
// Using parseInt to convert string to number
})
alert('after:\r' + id)
function updateQA(question, answer) {
return 'CourseContent1_activityContent34169_question1_answer0_ac'.replace(/^(.*question)(\d*)(_answer)(\d*)(.*)/gi, '$1' + question + '$3' + answer + '$5');
}
Here's a bit of a less verbose way of doing it:
var increment = function(_, prefix, n) { return prefix + (+n + 1) };
id.replace(/(question)(\d+)/, increment).replace(/(answer)(\d+)/, increment);
The parenthesized matches (i.e. the capturing groups) are passed as separate args to the replacement functions, and there you can just increment them and return with the corresponding prefix.

Removing quotes from a string / an alternative to string

I have dropDown element which takes the options in the format
ctrlOptions:{0:'String',1:'int'}
in addition to simple data types i have user defined data types hence i want to populate this dynamicaly . so i used a loop and concatenation
var dropDown = "{"
for(var i=0;i<dataTypesList.length;i++){
if(i == dataTypesList.length-1){
dropDown = dropDown + i + ":" + "'" + dataTypesList[i].Name + "'}";
}else{
dropDown = dropDown + i + ":" + "'" + dataTypesList[i].Name+ "'" + ",";
}}
This yields be the options in required format but along with quotes around it like
ctrlOptions:"{0:'String',1:'int'}"
i want to remove the double quotes i tried with replace it diesnt seem to help. how can i achieve this can i use any other way.
What you want to create is an object & not a string.
So wildly guessing from your code, that the input dataTypesList looks something like this:
dataTypesList = [{Name:'String'}, {Name:'int'}]
You should use :
var dropDown = {};
for(var i=0;i<dataTypesList.length;i++)
dropDown[i] = dataTypesList[i].Name;
And then Output is an object :
{0: "String", 1: "int"}
you can use JSON.parse to convert the options string from string json to object json:
Using your code (slightly modified):
var dropDown = "{"
for(var i = 0; i < dataTypesList.length; i++)
{
if(i === dataTypesList.length - 1)
{
dropDown += i + ":'" + dataTypesList[i].Name + "'}";
}
else
{
dropDown += i + ":'" + dataTypesList[i].Name + "',";
}
}
// later...
ctrlOptions: JSON.parse(dropDown);
Verify your target browsers are compatible: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If not, there are some libraries compatible with older browsers that do the same thing. JSON2 is recommended by the author for out-of-date browsers: https://github.com/douglascrockford/JSON-js

problem in fetching a particular cookie

This is the script that i am using to fetch a particular cookie lastvisit :
AFTER THE EDIT
// This document writes a cookie
// called from index.php
window.onload = makeLastVisitCookie;
function makeLastVisitCookie() {
var now = new Date();
var last = new Date();
now.setFullYear(2020);
// set the cookie
document.cookie = "lastvisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString();
var allCookies = document.cookie.split(";");
for( var i=0 ; i < allCookies.length ; i++ ) {
if(allCookies[i].split("=")[0]== "lastvisit") {
document.getElementById("last_visit").innerHTML = "You visited this site on" + allCookies[i].split("=")[1];
} else {
alert("testing..testing..");
}
}
}
From this script the if part never works though there are 5 cookies stored from my website. (including the cookie that i am saving from this script) What is the mistake that i am making while fetching the cookie named lastvisit ?
You're splitting the cookie by ; an comparing those tokens with lastvisit. You need to split such a token by = first. allCookies[i] looks like key=val and will never equal lastvisit. Een if allCookies[i] == "lastvisit" is true, the result will still not be as expected since you're showing the value of allCookies[i + 1] which would be this=the_cookie_after_lastvisit.
if(allCookies[i].split("=") == "lastvisit") { should be:
var pair = allCookies[i].split("=", 2);
if (pair[0].replace(/^ +/, "") == "lastvisit") {
"You visited this site on" + allCookies[i+1]; should be:
"You visited this site on" + pair[1];
The 2 argument of split makes cookies like sum=1+1=2 be read correctly. When splitting cookies by ;, the key may contain a leading space which much be removed before comparing. (/^ +/ is a regular expression where ^ matches the beginning of a string and + one or more spaces.)
Alternatively, compare it directly against a RE for matching the optional spaces as well (* matches zero or more occurences of a space character, $ matches the end of a string):
if (/^ *lastvisit$/.test(pair[0])) {
I've tested several ways to get a cookie including using regular expressions and the below was the most correct one with best performance:
function getCookie(name) {
var cookie = "; " + document.cookie + ";";
var search = "; " + encodeURIComponent(name) + "=";
var value_start = cookie.indexOf(search);
if (value_start == -1) return "";
value_start += search.length;
var value_end = cookie.indexOf(';', value_start);
return decodeURIComponent(cookie.substring(value_start, value_end))
}
You need to remove possible white space around the cookie key before comparing to the string "lastvisit". This is done conveniently using regular expressions. /^\s+/ matches all white space at the beginning, /\s+$/ matches all white space at the end. The matches are replaced by the empty string, i.e. removed:
for( var i = 0 ; i < allCookies.length ; i++ ) {
var c = allCookies[i].split("="); // split only once
var key = c[0].replace(/^\s+/, '').replace (/\s+$/, ''); // remove blanks around key
if (key == "lastvisit") {
document.getElementById("last_visit").innerHTML = "You visited on " + c[1];
}
//...
}

Adding characters to string (input field)

I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.
The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.
Any ideas as to how I could implement this?
Thanks
Zaps
function FormatTextBox(id) {
var txtBox = $(id).val();
//strip bracket to get the number only
txtBox = txtBox.replace("[", "").replace("]", "");
var val = parseFloat(txtBox);
if (val < 0) {
txtBox.val("[" + val + "]");
} else {
txtBox.val(val);
}
return val;
}
First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.
Number.prototype.bracketed = function() {
if(this < 0) {
return '[' + -this + ']';
} else {
return '' + this;
}
};
var result = do_calculation();
myTextBox.value = result.bracketed();
// result still holds the original Number value.
If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:
String.prototype.unbracketed = function() {
var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number
if(parts[1]) { // [number]
return -parseInt(parts[1], 10);
}
if(parts[2]) { // number
return parseInt(parts[2], 10);
}
return NaN;
};
Assuming you might have multiple fields (and you don't want the negative sign):
jQuery('input').each(function(){
if(jQuery(this).val() < 0 ){
jQuery(this).val('['+-1*jQuery(this).val()+']');
}
}
)
Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.
EDIT:
You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )

Categories

Resources