err variable space is undefined why? - javascript

I run next code and I miss somthing, for me it seem OK :
window.onload = TitleFieldInit;
function TitleFieldInit() {
var str = document.cookie.split("=")[1];
var space = str.split("=")[1];
space = space.split(";")[0];
alert(space);
// while( space.indexOf('%20' )+1) space = space.replace(/%20/,' ');
if (document.cookie != "") {
document.getElementById("TitleField").innerHTML = "Your Title is : " + space;
}
}​
and I got err in FireFox rror"space is undefined" why ?
In chrome "Uncaught TypeError:Cannot call method'split' of Undefined"
Thx for helping.

This code will never work for any input.
str is a already part of result of split by =, i.e. it contains no = symbols.
Then you split that result again by =, which of course will return you one-element array and str.split("=")[1] will always be undefined.
Looks like you're trying to read cookie value... but second .split("=") is not needed at all.
Ah, and you got different results in different browsers, cause they contain different data in their cookies.
PS: Instead of while( space.indexOf('%20' )+1) space = space.replace(/%20/,' '); you may write space = space.replace(/%20/g,' '); to replace all of them at once.

Related

JavaScript Error in Pentaho - Cannot call method "toUpperCase" of null

// Sets all the letters as uppercase
var str = ae_a_asset_e$manufacture_code.toUpperCase();
var str2 = ae_a_asset_e$serial_no.toUpperCase();
var str3 = ae_a_asset_e$manu_part_number.toUpperCase();
var str4 = ae_a_asset_e$region_code.toUpperCase();
var str5 = ae_a_asset_e$fac_id.toUpperCase();
Any idea how to fix this? I would think there would have to be a way to say if value = null then don't worry about it.
First you have to think whether it is correct that some values are null or not, such as ae_a_asset_e$manufacture_code.
If they can be null you can access them in a safe way like this (extend this code to all other vars as required):
var str = ae_a_asset_e$manufacture_code ? ae_a_asset_e$manufacture_code.toUpperCase() : "";
If they cannot be null then, your should check your data integrity first and then run this script (assuming they are never null).

Declare JavaScript variable only with ' ' marks

I saw one of the masters doing this:
var example = '';
Then later he continued with this:
example += '<div>just a div</div>';
I wanna know if there's any difference from doing this:
var example;
example += '<div>just a div</div>';
I don't really know if by doing the second method I'm doing wrong and I have to code like shown if the first example.
Updated!
Thank you so much for your answers, Ok I got it I need to define my variable to be able to work woth it, but then another question came... This master also is doing this:
var guess;
and then he does:
guess += myfunction( upper );
where myfunction was declared as follows:
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
So, why here is different? Can any of you answer this please?
Thank you!
Second update!
Again Thanks!
I decided to post the whole code the JS master was doing, at this point I don't understand, so probably you'll be able to clear my doubts.
var randomNumber = myFunction( 10 );
var guess;
var attempts = 0;
var answer = false;
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
do{
guess = prompt( "I created a number from 1 till 10, can you guess it?");
attempts += 1;
if( parseInt( guess ) === randomNumber ){
answer = true;
}
}while( ! answer )
document.write( "Took you " + attempts + " attempts to guess the number " + randomNumber);
Please have a look at:
var guess;
and how later is being declared, so why here works perfectly but in my first example I have to put the '' when declaring my variable?
I hope my question is clear enough for you!
Thank you for your time and patient!
When you do:
var example;
example += '<div>just a div</div>';
You end up with:
`"undefined<div>just a div</div>"`
This is because when you don't initialize a variable, it is undefined, which can be converted to a sensible string "undefined" when you try to add it to another string.
When you do:
var guess;
guess += myfunction( upper );
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
You are adding a number to undefined. This results in NaN (not a number) because undefined cannot be converted into a sensible number.
You can check this yourself next time by opening up your browser's developer tools and running the code in the console.
Edit:
When you do:
var guess;
guess = prompt( "I created a number from 1 till 10, can you guess it?");
There's no issue because you are simply assigning a string to the guess variable. In the previous examples you were adding something to a variable, which means if they are different types then JavaScript has to try to do something sensible.
If you don't initialize your variable it has a value of undefined.
In your last example, you are really saying example = undefined + '<div>just a div</div>' and undefined will be converted to a string and output that way. Probably not what you want.
In general it is a good idea to initialize your variables before you use them which is why var example = '' is preferable in this case.
var myvar
myvar += 'asdf'
console.log(myvar) // prints undefinedasdf
var othervar = ''
othervar += 'sdfasdf'
console.log(othervar) // prints sdfasdf
If you don't initialize the variable then it will be undefined
Appending to undefined object doesn't help.
var example = '';
Here you are initializing an empty string to the variable and therefore appending a string to another string will give the desired output of string concatenation.
Output:
"undefined<div>just a div</div>"
"<div>just a div</div>"
Yes there is a difference the first snipet from the master creates a variable example and gives it a default value, the second statement concatinates the value with 'just a div'
.Your code has an error as it is adding a value to a non-existed value as variable example has no default value.

Unexpected Token Illegal with onclick Java Script in Salesforce.com

I have been working on this most of the morning but to no end. I am trying to execute a button that uses OnClick Java in Salesforce.com and it keeps throwing errors. I think the issue may be with special characters in the data as it works when I simply use just text. But any time numbers or any special characters are present I get the error "unexpected token ILLEGAL". Can anyone help me to see what I am doing wrong and how I can get away from failing when special characters are involved?
{!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")}
var opptyObj = new sforce.SObject("Opportunity");
var caseObj = new sforce.SObject("Case");
var today = new Date();
var sOpptyId = "{!Case.Opportunity__c}";
if( sOpptyId != "")
{
alert("This case is already tied to an opportunity!");
}
else
{
opptyObj.AccountId = "{!Case.AccountId}";
opptyObj.CloseDate = sforce.internal.dateTimeToString(today);
opptyObj.Description="{!Case.Description}";
opptyObj.Case__c = "{!Case.Id}";
opptyObj.Name = "{!Case.Subject}";
opptyObj.StageName = "Estimate in Progress";
opptyObj.Created_from_Case__c = "Y";
opptyObj.Type = "New Business";
opptyObj.Amount = ".01";
var opptyresult = sforce.connection.create([opptyObj]);
if (opptyresult[0].success=='false')
{
alert("Opportunity creation failed: " + opptyresult[0].errors.message);
}
else
{
caseObj.Id = '{!Case.Id}';
caseObj.Opportunity__c = opptyresult[0].id;
caseObj.Status = "Estimate in Progress";
var caseResult = sforce.connection.update([caseObj]);
if(caseResult[0].success == 'false')
{
alert("Case update failed: " + caseResult[0].errors.message);
}
else
{
alert("An opportunity has been created and linked to this case.");
location.reload(true);
}
}
}
Assuming this is some kind of template, whatever is rendering this needs to properly escape some values in the strings it's inserting.
Given this:
opptyObj.Description="{!Case.Description}";
Let's say I enter a description consisting of this:
"That is awesome," said John.
When that is rendered in your template the result is this:
opptyObj.Description=""That is awesome," said John.";
As you might be able to see, the result is a syntax error.
You need to escape quote characters in an text inserted this way. And without knowing what is technology rendering this template I can't give you any specifics, but you want to replace " with \" and ' with \'. The \ escapes characters, forcing them to be treated as literal characters in the string instead of other special meaning.
This must be done as it's being inserted into the script. Something in the spirit of this:
opptyObj.Description="{!Case.Description.replace(/'/, "\\'").replace(/"/, '\\"')}
Exactly how to do that depends on what language or template engine is being used here. But th eresult should look like this:
opptyObj.Description="\"That is awesome,\" said John.";
Ruby on Rails implements an escape_javascript method, which sanitizes data for injection into Javascript. It does the following replacements. It seems like a good baseline.
'\\' => '\\\\'
'</' => '<\/'
"\r\n" => '\n'
"\n" => '\n'
"\r" => '\n'
'"' => '\\"'
"'" => "\\'"
UPDATE:
According to this: http://www.salesforce.com/us/developer/docs/pages/Content/pages_security_tips_scontrols.htm
It looks like you want the JSENCODE function. Something like this, perhaps?
opptyObj.Description="{!JSENCODE(Case.Description)}";

Javascript splitting string using only last splitting parameter

An example of what im trying to get:
String1 - 'string.co.uk' - would return 'string' and 'co.uk'
String2 - 'random.words.string.co.uk' - would return 'string` and 'co.uk'
I currently have this:
var split= [];
var tld_part = domain_name.split(".");
var sld_parts = domain_name.split(".")[0];
tld_part = tld_part.slice(1, tld_part.length);
split.push(sld_parts);
split.push(tld_part.join("."));
With my current code, it takes the split parameter from the beginning, i want to reverse it if possible. With my current code it does this:
String1 - 'string.co.uk' - returns 'string' and 'co.uk'
String2 - 'random.words.string.co.uk' - would return 'random` and 'words.string.co.uk'
Any suggestions?
To expand upon elclanrs comment:
function getParts(str) {
var temp = str.split('.').slice(-3) // grabs the last 3 elements
return {
tld_parts : [temp[1],temp[2]].join("."),
sld_parts : temp[0]
}
}
getParts("foo.bar.baz.co.uk") would return { tld_parts : "co.uk", sld_parts : "baz" }
and
getParts("i.got.99.terms.but.a.bit.aint.one.co.uk") would return { tld_parts : "co.uk", sld_parts : "one" }
try this
var str='string.co.uk'//or 'random.words.string.co.uk'
var part = str.split('.');
var result = part[part.length - 1].toString() + '.' + part[part.length - 1].toString();
alert(result);
One way that comes to mind is the following
var tld_part = domain_name.split(".");
var name = tld_part[tld_part.length - 2];
var tld = tld_part[tld_part.length - 1] +"."+ tld_part[tld_part.length];
Depending on your use case, peforming direct splits might not be a good idea — for example, how would the above code handle .com or even just localhost? In this respect I would go down the RegExp route:
function stripSubdomains( str ){
var regs; return (regs = /([^.]+)(\.co)?(\.[^.]+)$/i.exec( str ))
? regs[1] + (regs[2]||'') + regs[3]
: str
;
};
Before the Regular Expression Police attack reprimand me for not being specific enough, a disclaimer:
The above can be tightened as a check against domain names by rather than checking for ^., to check for the specific characters allowed in a domain at that point. However, my own personal perspective on matters like these is to be more open at the point of capture, and be tougher from a filtering point at a later date... This allows you to keep an eye on what people might be trying, because you can never be 100% certain your validation isn't blocking valid requests — unless you have an army of user testers at your disposal. At the end of the day, it all depends on where this code is being used, so the above is an illustrated example only.

Regex escaping bracket in javascript not working

I've got a chunk of code that is doing something really strange.
function getQuerystring(key, default_){
if (default_==null) default_="";
key = key.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
var isThankyou = getQuerystring('CONFIRMATION');
This function checks the URL for a parameter (in this case CONFIRMATION). From what I can tell everything is correct, but when the browser loads the code it throws an error in the console.
Uncaught SyntaxError: Invalid regular expression: missing /
Ultimately this chunk of code is used to determine if a user is on the confirmation page of the URL. If they are then it triggers some google analytics code to track ecommerce purchase information in GA.
The line that is giving me trouble is:
key = key.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
When I load the page in the browser and look at the source this is what shows up:
key = key.replace(/[\[]/,'\\\[').replace(/[\/,'\\\]');
with two ]] showing up just before
Here's the weird thing. When I duplicate the line commenting out the first one, the error doesn't get thrown (the ]] still shows up however):
//key = key.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
key = key.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
I've tried everything I can think of with no success, I've even tried unchaining the replace method in case that was causing the issue.
key = key.replace(/[\[]/,'\\\[');
key = key.replace(/[\]]/,'\\\]');
Which results in the following in the browser source:
key = key.replace(/[\[]/,'\\\[');
key = key.replace(/[\/,'\\\]');
In any case, the issue seems to be with the second .replace not escaping the one ] or even keeping the two ]] for some reason.
I've also tried erasing cache, cookies, and turning off all plugins. I've tested in Chrome, Firefox, and Safari with the same results on all 3 browswers.
Here is the page that you can see the full block of code (last in the head): https://secure2.convio.net/ccod/site/Ecommerce?store_id=2841
Your code looks a bit complex. Here's something simpler:
function getQueryString(key) {
var index, url, parts, i, subparts;
url = window.location.href;
index = url.indexOf("?");
if (index === -1) {
return null;
}
url = url.substr(index);
parts = url.split("&");
for (i = 0; i < parts.length; i += 1) {
subparts = parts[i].split("=");
if (subparts[0] === key) {
return subparts[1];
}
}
return null;
}
(untested)
This causes an error: key = key.replace(/[\/,'\\\]') because you escape the forward slash at the end of the regex with a back-slash like this: /[\/
Try this instead key = key.replace(/[\\/,'\\\]')

Categories

Resources