Invalid or unexpected token referencing HTML in JS - javascript

Code:
(function () {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.Templates.Header = “<div><b>Announcements</b></div><table>”; <---syntax error here?
itemCtx.Templates.Item = ItemOverrideFun;
itemCtx.Templates.Footer = “</table>”; <---syntax error here?
itemCtx.BaseViewID = 1;
itemCtx.ListTemplateType = 104;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
})();
function ItemOverrideFun(ctx) {
var _announcementTitle = ctx.CurrentItem.Title;
var _announcementDesc = ctx.CurrentItem.Body;
var _announcementID = ctx.CurrentItem.ID;
return “<tr><td><p><b>” + _announcementTitle + “</b></p>” + _announcementDesc +”<a href=’/Lists/Company%20Announcements/DispForm.aspx?ID=’+ _announcementID +’> Read More…</a></td></tr>”; <---syntax error here?
}
When this code is called the Chrome console says there's a invalid or unexpected token syntax error.
The error displays on lines with the double quotes and in the Chrome console the double quotes are actually replaced with icons that look like diamonds with question marks in them.
So far I've tried swapping them with single quotes and encasing the double quotes in single quotes, neither has worked.
Thank you.

Lal made a good point. I've fixed it below.
Here:
(function () {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.Templates.Header = "<div><b>Announcements</b></div><table>";
itemCtx.Templates.Item = ItemOverrideFun;
itemCtx.Templates.Footer = "</table>";
itemCtx.BaseViewID = 1;
itemCtx.ListTemplateType = 104;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
})();
function ItemOverrideFun(ctx) {
var _announcementTitle = ctx.CurrentItem.Title;
var _announcementDesc = ctx.CurrentItem.Body;
var _announcementID = ctx.CurrentItem.ID;
return "<tr><td><p><b>" + _announcementTitle + "</b></p>" + _announcementDesc +"<a href='/Lists/Company%20Announcements/DispForm.aspx?ID=" _announcementID +"'> Read More…</a></td></tr>";
This was the problem:
”<a href=’/Lists/Company%20Announcements/DispForm.aspx?ID=’+ _announcementID +’>
You had tried to close the string with the single quote, you needed a double to close it before you concatenated _announcementID

Replace “ with "
As the error message shown in the console, there is clearly an error in the “ that you are using. The “ that you are using is not the same as " that is to be used.
Thus, replace all the occurences of “ with ".
“ is LEFT DOUBLE QUOTATION MARK and " is QUOTATION MARK . You should understand that
both are different.
Check this for “ and see this for ".

You need to replace all the single quotes and double quotes with the proper characters then quote the other fragment of the link properly with the double quotes: _announcementID+"'> Read More...</a>
(function () {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.Templates.Header = "<div><b>Announcements</b></div><table>";
itemCtx.Templates.Item = ItemOverrideFun;
itemCtx.Templates.Footer = "</table>";
itemCtx.BaseViewID = 1;
itemCtx.ListTemplateType = 104;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
})();
function ItemOverrideFun(ctx) {
var _announcementTitle = ctx.CurrentItem.Title;
var _announcementDesc = ctx.CurrentItem.Body;
var _announcementID = ctx.CurrentItem.ID;
return "<tr><td><p><b>" + _announcementTitle + "</b></p>" + _announcementDesc +"<a href='/Lists/Company%20Announcements/DispForm.aspx?ID="+ _announcementID+"'> Read More...</a></td></tr>";
}

Related

JSON Parse causing 'undefined' json values - Javascript

I have searched far and wide for answers to my problem but I am just not winning, I am hoping someone will be kind enough to offer me some guidance.
My below Javascript code is returning undefined json values:
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\ProgramTest\\"}'
var stringified = JSON.stringify(req);
console.log('stringified json ' + stringified);
//json = JSON.parse(JSON.stringify(stringified))
var json = JSON.parse(stringified );
console.log('parsed json ' + json);
//testing different ways of pulling out the data, all undefined
var testId = json["testId"];
var ruleId = json.ruleId;
var testValue = json[testValue];
console.log('testValue ' + testValue);
var rulePassed = Boolean(json[rulePassed]);
njson = '{"testId": "' + testId + '","ruleId": "' + ruleId + '","testValue": "' + testValue + '","rulePassed": ' + rulePassed + '}';
console.log('final json ' + njson);
The complication comes in with the backslash in the testValue property.
If I do not stringify the json first, I receive the following error:
SyntaxError: Unexpected token P in JSON at position 143
As soon as I Stringify however, and then parse, the values come back as undefined.
Does anybody perhaps know what I am doing wrong please?
Thanks
If you know that your data will never properly escape backslashes, a quick solution is the following:
var req_escaped = req.replace(/\\/g, "\\\\") // escape backslashes
JSON.parse(req_escaped)
Basically, make your string JSON compliant and then use the usual parsed method.
replacing the backslashes compiles. also you need to add " around testValue when you get it from the json
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\ProgramTest\\"}';
var req_escaped = req.replace(/\\/g, "\\\\") // escape backslashes
var json = JSON.parse(req_escaped);
console.log(json);
var testId = json["testId"];
var ruleId = json.ruleId;
var testValue = json["testValue"];
console.log('testValue ' + testValue);
var rulePassed = Boolean(json[rulePassed]);
njson = '{"testId": "' + testId + '","ruleId": "' + ruleId + '","testValue": "' + testValue + '","rulePassed": ' + rulePassed + '}';
console.log('final json ' + njson);
If you have control over the escaping process, the backslashes path should be escaped as follows:
\\ should be \\\\
The first escape escapes it in the Javascript string literal. The second escape escapes it in the JSON string literal. Credits and more details.
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\\\ProgramTest\\\\"}'
console.log(JSON.parse(req))

How to correctly evaluate Javascript string containing JSON.parse expression with special characters?

I need to evaluate a JS expression created in the following way
function createExprs(obj){
var decl = "var i = ";
var value = JSON.stringify(obj);
var exprs = decl + "JSON.parse('" + value + "')";
return exprs;
}
var i = createExprs({1:2});//i = "var i = JSON.parse('{"1":4}')"
eval(i); // works fine
However it fails when the obj contains any special characters
var i = createExprs("today\\.article") \\i="var i = JSON.parse('"today\\.article"')"
eval(i) // Unexpected token . in JSON
You need to escape the ":
"var i = JSON.parse('\"today.article\"')"

regex replace jumbles string

This is my console.log:
str : +0-D : replace : Da href="Javascript:PostRating('','|P|622','+0')">+0</a>-D
I have the following function:
function replaceAll_withMatching(str, find, rep, prodId) {
//console.log(str + " : " + find + " : " + rep + " : " + prodId);
var returnString = "";
if (find.toLowerCase() == str.toLowerCase()) {
returnString = rep;
} else {
escfind = "\\" + find ;
var regexp = new RegExp(escfind, "i");
var match = regexp.test(str);
if (match) {
var regAHREF = new RegExp("\\<a", "i");
var AHREFMatch = regAHREF.test(str);
if (AHREFMatch == false) {
str = str.replace(regexp, rep);
str = replaceProductAll(str, PRODUCT_PLACEHOLD, prodId);
} else {
var aTagText = $($.parseHTML(str)).filter('a').text();
if ((find !== aTagText) && (aTagText.indexOf(find) < 0)) {
console.log(regexp);
console.log("str : " + str + " : replace : " + str.replace(regexp, rep));
str = str.replace(regexp, rep);
}
}
}
//console.log(str);
returnString = str;
}
//returnString = replaceProductAll(returnString, PRODUCT_PLACEHOLD, prodId);
return returnString;
}
This function looks for a "<a>" tag, if it doesn't find one then it does the replace. If it does find one it has some conditions that if everything checks out it does another replace.
The string that I'm passing in has been already "parsed" on the +0:
+0-D
In the second pass I'm expecting it to find the "D" in the above string, and then do the following replacement:
D
But as you can see, after the 2nd replace it is jumbling the string and producing malformed HTML
Da href="Javascript:PostRating('','|P|622','+0')">+0</a>-D
More Context:
I have a string that needs to have a replace done on it. This is existing code so I'm not in a position to rework the function.
The original string is: +0-D
This string gets passed into the function below multiple times looking for matches and then if it finds a match it will replace it with the value (also passed in as a parameter).
When the +0-D gets passed in the first time the +0 is matched and a replace is done: +0
Then the next time the string is passed in: +0-D. The function finds the D as a match and it looks like it attempts to do a replace. But it is on this pass that the string gets jumbled.
Ultimately what I'm expecting is this:
+0-D
This is what I'm currently getting after the 2nd attempt:
Da href="Javascript:PostRating('','|P|622','+0')">+0</a>-D
Further Context:
The +0-D is one of many strings this function handles. Some are very simple (i.e. Just +0), others are much more complex.
Question:
Based on the above, what do I need to do to get the regex to not jumble the string?
The problem was in the escfind:
escfind = "\\" + find;
var regexp = new RegExp(escfind,"i");
var match = regexp.test(str);
The first thing I did was in the 2nd replace clause I created a new RegExp to not use the "\\" + find;
if((find !== aTagText) && (aTagText.indexOf(find) < 0)){
try{
var regexp2 = new RegExp(find,"i");
var match2 = regexp2.test(str);
console.log(str.replace(regexp2,rep));
}catch(err){
console.log(err);
}
}
Then my string began to return as expected, however, when I opened it up to all the variations I was getting the Unexpected quantifier error.
Then I found this question - which lead me to escape out my find:
Once I replaced my code with this:
escfind = find.replace(/([*+.?|\\\[\]{}()])/g, '\\$1');
Then I got the output as expected:
<a href='+0'>+0</a>-<a href='D'>D</a>

Regex mapping in Firefox context menu contentScript

I am developing context menu add-on for Firefox. I am trying to get the selectedText and validate if it is a number. If it is a number i am using that number value to process further.
But, i got stuck at a point where i am trying to replace [(,)] using regex in javascript replace method.
Following is the code which fails to map any number starting/ending with ( or ):
var menuItemLRG = contextMenu.Item({
label: "LRG",
data: "http://myurl/&val=:",
contentScript: 'self.on("click", function (node, data) {' +
' var selectedText = window.getSelection().toString();' +
' var formattedText1 = selectedText.trim();' +
' var formattedText2 = formattedText1.replace(/^[,\[\]()]*/g,"");' +
' var formattedText3 = formattedText2.replace(/[,\[\]()]*$/g,"");' +
' console.log(formattedText3); '+
' var regExp = new RegExp(/^[0-9]+$/);' +
' if (regExp.test(formattedText3) == true) {' +
' console.log("URL to follow :"+data+formattedText3);' +
' window.open(data+formattedText3);' +
' } '+
'});'
});
Above code fails to replace ( or ) in sample inputs: (5663812, 11620033).
But, a vanilla test like the following succeeds:
<script>
var str = "(2342423,])";
var tmpVal1 = str.replace(/^[,\[\]()]*/g,"");
var tmpVal2 = tmpVal1.replace(/[,\[\]()]*$/g,"");
var regExp = new RegExp(/^[0-9]+$/);
if (regExp.test(tmpVal2) == true) {
alert(tmpVal2);
}
</script>
After many trial and error found the issue. When we try to escape a character inside a single quotes we need to add one more escape for the escape character to get recognized, otherwise the single escape \] will be considered as ] which leads to abrupt ending of of the regex pattern.
In this case:
' var formattedText2 = formattedText1.replace(/^[,\[\]()]*/g,"");'
is decoded as :
var formattedText2 = formattedText1.replace(/^[,[]()]*/g,"");
instead of as:
var formattedText2 = formattedText1.replace(/^[,\[\]()]*/g,"");
So, by adding one more escape character for an escape character resolved the pattern correctly:
' var formattedText2 = formattedText1.replace(/^[,\\[\\]()]*/g,"");'
Sorry for wasting your time in analyzing the cause, if any.

Javascript regex with variable

I have the following string in a variable named js:
some code here
/* start-rotateControlOptions */
some more code here
on multiple
lines
/* end-rotateControlOptions */
some code here
And I want to end up with:
some code here
some code here
Basically escape everything between these 2 specific comments.
The following works:
js = js.replace(/\/\* start-rotateControlOptions \*\/([\s\S]*)\/\* end-rotateControlOptions \*\//, '');
But now I need to have the rotateControlOptions as a variable.
This is what I have tried to no avail:
js = escapeCode(js, 'rotateControlOptions');
function escapeCode(js, identifier) {
var re = new RegExp("/\/\* start-" + identifier + " \*\/([\s\S]*)\/\* end-" + identifier + " \*\//");
js = js.replace(re, '');
return js;
}
What am I doing wrong? I get no error.
Escape all the backslahes one more time and you don't need to add the forward slash delimiter inside the RegExp constructor.
var re = new RegExp("/\\* start-" + identifier + " \\*/([\\s\\S]*)/\\* end-" + identifier + " \\*/");
Example:
> var str = 'some code here\n/* start-rotateControlOptions */\nsome more code here\non multiple\nlines\n/* end-rotateControlOptions */\nsome code here';
> var re = new RegExp("/\\* start-" + identifier + " \\*/([\\s\\S]*)/\\* end-" + identifier + " \\*/\\n");
undefined
> console.log(str.replace(re, ''))
some code here
some code here

Categories