SyntaxError: unterminated string literal in PHP variable - javascript

I search through the numerous questions already asked about the "unterminated string literal" syntax error but found nothing helping me ...
So, I have this Javascript function :
function parametresModal($parametres) {
document.getElementById('remodalTest').innerHTML = $parametres;
};
Then I call this function on a link in my page :
<a href="#" onClick='parametresModal("<?php the_field('description-defi'); ?>");'>TEST</a>
The parameter written here is simplified ; I actually want to add this Wordpress ACF's function among others and HTML markup, but I found the issue was appearing with this particular field (see below).
This "parametresModal" function is supposed to fill the following div with its parameters :
<div id="remodalTest">MyDiv</div>
Problem is the console outputs
"SyntaxError: unterminated string literal"
The Wordpress ACF's field "description-defi" contains a few lines of text with some simple quotes (ex. c'est, l'éviter, ...).
So I tried to escape the quotes with several methods :
$myField = the_field('description-defi');
$myEscape = json_encode($myField);
or
$myField = the_field('description-defi');
$myEscape = addshlashes($myField);
or
$myField = the_field('description-defi');
$myEscape = htmlspecialchars($myField);
Always resulting in the same error.
Do you see where I could be wrong in my code or my way of thinking the thing ?
Thank you very much !

the_field() will output the content of the selected field. If you want to work with a field, you should use get_field() instead.
See: https://www.advancedcustomfields.com/resources/the_field/
Also the newline character will not be escaped by any of PHP's escape functions, if your String contains newlines, you will need to escape them manually using something like this: $myField = str_replace(array("\r\n", "\n"), "<br>", $myField);.
If you know that your DB will consistently use the same newline sequence, you can replace array("\r\n", "\n") by that newline sequence instead.

Related

Break javascript string

I have a javascript script string :
var link=C:\test\pictures\myimage\upload\1464592985595_151.jpg
I want to get following 1464592985595_151.jpg
I am using this to split but getting error in java script
link= link.split("\");
Error: unterminated string literal
How can I solve this problem ?
your link needs to be wrapped in ' signs like this:
var link='C:\test\pictures\myimage\upload\1464592985595_151.jpg';
Also, \ is used to escape characters so you have to escape the escaping:
link= link.split("\\");
From here it's just a matter of selecting the last piece:
console.log(link[link.length -1]; //Outputs '1464592985595_151.jpg'
My suggestion to you would be to find a nice coding tool with syntax highlighting like visual studio code to help you catch these things.
Check It .
var link="C:/test/pictures/myimage/upload/1464592985595_151.jpg";
var linkarray=link.split("/");
var myimage= linkarray[linkarray.length-1];
alert(myimage);
Note- avoid to use backslash (\) in string, because javascript take it
as a escape character.

Javascript How to escape \u in string literal

Strange thing...
I have a string literal that is passed to my source code as a constant token (I cannot prehandle or escape it beforehand).
Example
var username = "MYDOMAIN\tom";
username = username.replace('MYDOMAIN','');
The string somewhere contains a backslash followed by a character.
It's too late to escape the backslash at this point, so I have to escape these special characters individually like
username = username.replace(/\t/ig, 't');
However, that does not work in the following scenario:
var username = "MYDOMAIN\ulrike";
\u seems to introduce a unicode character sequence. \uLRIK cannot be interpreted as a unicode sign so the Javascript engine stops interpreting at this point and my replace(/\u/ig,'u') comes too late.
Has anybody a suggestion or workaround on how to escape such a non-unicode character sequence contained in a given string literal? It seems a similar issue with \b like in "MYDOMAIN\bernd".
I have a string literal that is passed to my source code
Assuming you don't have any < or >, move this to inside an HTML control (instead of inside your script block) or element and use Javacript to read the value. Something like
<div id="myServerData">
MYDOMAIN\tom
</div>
and you retrieve it so
alert(document.getElementById("myServerData").innerText);
IMPORTANT : injecting unescaped content, where the user can control the content (say this is data entered in some other page) is a security risk. This goes for whether you are injecting it in script or HTML
Writing var username = "MYDOMAIN\ulrike"; will throw a syntax error. I think you have this string coming from somewhere.
I would suggest creating some html element and setting it's innerHTML to the received value, and then picking it up.
Have something like:
<div id="demo"></div>
Then do document.getElementById("demo").innerHTML = username;
Then read the value from there as document.getElementById("demo").innerHTML;
This should work I guess.
Important: Please make sure this does not expose the webpage to script injections. If it does, this method is bad, don't use it.

Escape Quote - javascript, struts 2

I read some struts2 variable in javascript as follows:
<javascript type="text/javascript">
var data='<s:property value="simulationInfos"/>';
<javascript>
If my simulationInfos contains single quote ', I get the error : unexpected identifier.
therefore, I tried to escape the quote as follows:
var data='<s:property value="simInfos" escapeJavaScript="true"/>';
and var data='<s:property value="simInfos" escapeHTML="true"/>';
I get the error: Attribute escapeJavaScript (or escapeHTML) invalid for tag property according to TLD.
Any Idea?
If you want to use the inbuilt escapeJavascript of <s:property>, then upgrade to 2.2.1 Also in JavaScript, you can easily avoid unexpected identifier error if you had used double quotes.
var data = "<s:property value="simulationInfos"/>";
Where does the single quote appear? In the value, I'm assuming?
In that case, in your javascript before you perform the struts2 operation, do run this code on the value. This is a regular expression to remove quotations for javascript.
var escapedString = valueString.replace(/(['"])/g, "\\$1"); //note, includes double quotes
If you need to keep the quotes as URL encoded, do this
var escapedString = valueString.replace(/(['])/g, "&apos;");

javascript regex invalid quantifier error

I have the following javascript code:
if (url.match(/?rows.*?(?=\&)|.*/g)){
urlset= url.replace(/?rows.*?(?=\&)|.*/g,"rows="+document.getElementById('rowcount').value);
}else{
urlset= url+"&rows="+document.getElementById('rowcount').value;
}
I get the error invalid quantifier at the /?rows.*?.... This same regex works when testing it on http://www.pagecolumn.com/tool/regtest.htm using the test string
?srt=acc_pay&showfileCL=yes&shownotaryCL=yes&showclientCL=no&showborrowerCL=yes&shownotaryStatusCL=yes&showclientStatusCL=yes&showbillCL=yes&showfeeCL=yes&showtotalCL=yes&dir=asc&closingDate=12/01/2011&closingDate2=12/31/2011&sort=notaryname&pageno=0&rows=anything&Start=0','bodytable','xyz')
In this string, the above regex is supposed to match:
rows=anything
I actually don't even need the /? to get it to work, but if I don't put that into my javascript, it acts like it's not even regex... I'm terrible with Regex period, so this one has me pretty confused. And that error is the only one I am getting in Firefox's error console.
EDIT
Using that link I posted above, it seems that the leading / tries to match an actual forward slash instead of just marking the code as the beginning of a regex statement. So the ? is in there so that if it doesn't match the / to anything, it continues anyway.
RESOLUTION
Ok, so in the end, I had to change my regex to this:
/rows=.*(?=\&?)/g
This matched the word "rows=" followed by anything until it hit an ampersand or ran out of text.
You need to escape the first ?, since it has special meaning in a regex.
/\?rows.*?(?=\&)|.*/g
// ^---escaped
regtest.htm produces
new RegExp("?rows.?(?=\&)|.", "") returned a SyntaxError: invalid
quantifier
The value you put into the web site shouldn't have the / delimiters on the regex, so put in ?rows.*?(?=\&)|.* and it shows the same problem. Your JavaScript code should look like
re = /rows.*?(?=\&)|.*/g;
or similar (but that is a pointless regex as it matches everything). If you can't fix it, please describe what you want to match and show your JavaScript
You might consider refactoring you code to look something like this:
var url = "sort=notaryname&pageno=0&rows=anything&Start=0"
var rowCount = "foobar";
if (/[\?\&]rows=/.test(url))
{
url = url.replace(/([\?\&]rows=)[^\&]+/g,"$1"+rowCount);
}
console.log(url);
Output
sort=notaryname&pageno=0&rows=foobar&Start=0

Passing strings with Single Qoute from MVC Razor to JavaScript

This seems so simple it's embarrassing. However, the first question is when passing a value from the new ViewBag in MVC 3.0 (Razor) into a JavaScript block, is this the correct way to do it? And more importantly, where and how do you apply the proper string replacement code to prevent a single quote from becoming &#39 as in the resultant alert below?
Adding this into a single script block:
alert('#ViewBag.str') // "Hi, how's it going?"
Results in the following alert:
Razor will HTML encode everything, so to prevent the ' from being encoded to ', you can use
alert('#Html.Raw(ViewBag.str)');
However, now you've got an actual ' in the middle of your string which causes a javascript error. To get around this, you can either wrap the alert string in double quotes (instead of single quotes), or escape the ' character. So, in your controller you would have
ViewBag.str = "Hi, how\\'s it going?";
Another solution to use JSON string:
C#
ViewBag.str = "[{\"Text\":\"Hi, how's it going?\"}]";
Javascript
var j = #Html.Raw(ViewBag.str);
alert (j[0].Text);

Categories

Resources