Javascript: how to include a string literal into another one? - javascript

Say we've got a tag as follows:
<div ng-init="html='<a ng-click=\'openPopover(\'#ChoixDeLaDensiteRecherche\')\'>click</a>'"></div>
(I actually need to set variables with HTML code)
This doesn't work. How to write escaping for the innermost simple quotes?
PS: I don't know why \" \" didn't worked either.
[EDIT 1] The lecture error:
[Error] Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 12-12 [] in expression [openPopover(].

Try ", example:
<div onclick="alert('<a ng-click="openPopover(\'#ChoixDeLaDensiteRecherche\')">click</a>')">AAAAA</div>

Is there a reason why you're not closing the literal within the parentheses? It seems like you've escaped the closing quote outside the parentheses.
Try this:
<div onclick="alert('<a ng-click="openPopover(\'#ChoixDeLaDensiteRecherche\')">click</a>')">click</div>

Related

SyntaxError: unterminated string literal in PHP variable

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.

html syntax error in jQuery.ajax funciton?

I am manipulating the jSON array in the $.ajax function and i got confused with its syntax. There is a error and can't find it.
if(value['newVar'] === 1)
{
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
<a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
<span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span>\n\
<br/><br/>REMOVE</div>");
}
Error is in the if block and in the 4th line after RS."+value['price']+"</span>\n\ it says missing statement Uncaught SyntaxError: missing ) after argument list. I think the error is in the way I have written onclick="foo(this)"
Any help?
Replace the double quotes with single quotes. You are terminating the string with the double quotes and creating a syntax error:
...<a href='#' onclick='foo(this)' pid='"+value['id']+"'>
The error was due to a quote misuse on the last line: onclick="foo(this)".
You also had two single quotes missing...
(inside the string somewhere... Not causing the actual error, but you would had some errors in the produced HTML later).
You can use the quote of your choice as the string wrapper to append...
And the other for inside the string.
But you have to watch out for not "mixing" them!
One is the string wrapper and the other is part of the string.
if(value['newVar'] === 1){
$productContainer.append("<div id='productBox' class='grid_3'>\n"+
"<a href='product.jsp?id='" +value['id']+ "'><img src='" +value["image"]+ "'/></a><br/>\n"+
"<a href='product.jsp?id='" +value['id']+ "'><span class='black'>" +value['name']+ "</span></a><br/>\n"+
"<span class='black'>By " +value['company']+ "</span><br/><span class='red'>RS." +value['price']+ "</span>\n"+
"<br/><br/>REMOVE</div>");
}
Tricks:
Concatenate your lines using the + sign.
It prevent the inclusion of multiple tabs and spaces inside the string.
It is a better practice than your trailling slash \ at the end of each line.
Make your variables more evident visually, to be able to better see them, like I did above.
It also helps checking for missing or misused quotes.

Getting Lexer Error with AngularJS and ng-pattern

I'm getting the following error at runtime:
Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 11-11 [\] in expression [[0-9]{1,4}(\.[0-9]{1,3})?].
My HTML looks like this
<input type="text"
class="form-control"
name="amount"
ng-pattern="{{ctrl.pattern}}"
ng-model="ctrl.amount">
The assignment in my AngularJS controller is as follows:
ctrl.pattern = '[0-9]{1,4}(\\.[0-9]{1,3})?';
From what I understand AngularJS appends the ^ and $ at the beginning and end of regular expressions and that works great. The problem is that the regex literal in the middle of the expression is not being accepted. I want to dot to be accepted as a literal and not as any character so I need a way to escape it yet the lexer does not to like it. Is there a way around this?
This issue is already reported here but they are not going to fix it as according to them its a uncommon usecase.
Do it this way instead:
ctrl.pattern = /^[0-9]{1,4}([.][0-9]{1,3})?$/;
This way the regex will be evaluated as a regex object instead of a string parameter to RegExp in which case we will need to add ^,$

JSON.parse get "Uncaught SyntaxError: Unexpected token h"

I get the syntax error when I try to pass the following string:
JSON.parse("[{\"Date\": \"4/4/2016 4:15:19 PM\", \"Message\":\"<h3>New
Message</h3> Generated at 4/4/2016 4:15:19 PM.<br/><br/>Heavy Responsive
URL: <a href=\"https://performingarts.withgoogle.com/en_us\" ></a><br/><br/>
<img src=\"https://s-media-cache-ak0.pinimg.com/236x/06/bd/ac/06bdacc904c12abdce3381ba1404fd7e.jpg\" /> \"} ]");
I know that the error come from the link when I use double quote.
If I use single quote then no issue, but the data is getting from server side, I got no control over what going to pass in so I can only control on my side.
From what I read from the internet so far, I tried the following:
Use JSON.stringify first, then only use JSON.parse. I can parse
with no issue but problem occur when I try to loop the data. Instead
of looping it as JSON, the loop take the data as string and loop
every single text.
Escape every double quote which I'm currently doing, but it's not
working as shown above. But if I replace every double quote to
literal, I'm afraid some of the message that suppose to be double
quote will turn into literal as well, which will result in weird
looking message.
Please advice what other alternative I have to solve this.
You have JSON embedded in a JavaScript string literal.
" and \ are special characters in JSON and are also special characters in a JavaScript string literal.
href=\"https: escapes the " in the JavaScript string literal. It then becomes a " in the JSON. That causes an error.
When you want the " as data in the JSON you must:
Escape the " for JavaScript (as you are doing already)
Escape the " for JSON by adding a \.
Escape the \ for JavaScript
href=\\\"https:

how to put single double quotes together?

I have the following php code.
$msg .='<span>reply</span>';
When I click this anchor tag, I get the following error in console.
SyntaxError: illegal character # in myemail#company.com
I know the problem is due to single double quotes but don't know how to put the correct quotes.Can anyone help me please.
You can use backslash to use quotes as part of string
And in javascript, when passing str data to function it need to be in quotes.
$msg .='<span>reply</span>';
You can escape them with: "

Categories

Resources