Error: JSON array contains unterminated string literal

Hey there,

 var favorites = 'Array (


[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]

)
';

I've been encountering a syntax error - an unterminated string literal when I try to display the above content using console.log in JavaScript. I tried changing some characters and using regex patterns, but it seems like multi-line strings are causing an issue.

This dilemma began with an SQL query as seen below...

$favLinks = [];
$favQuery = "SELECT * FROM userfavorites WHERE users = '$username'";
$favResults = mysqli_query($conn, $favQuery);

while($row = mysqli_fetch_assoc($favResults)) {

array_push($favLinks, $row['fav_id']);

Then, I attempted this...

var favorites = <?php print_r ($favLinks); ?>

which resulted in the earlier mentioned problem.

If you have any suggestions on fixing this syntax error, I'd greatly appreciate it. Thanks!

Answer №1

Since multiline strings are not permitted in JavaScript:

"A
 B"

This will result in a syntax error. You can either replace the newlines with \n or use template literals like so:

`A
 B`

In your code snippet:

var newfavz =` <?php print_r ($favurl); ?>`;

Even though you fixed the error, the string is still not usable and needs to be parsed. Consider using JSON or creating your own parser.

Answer №2

To create a multiline string in JavaScript, remember to add a backslash at the end of each line:

const newFavorites = 'Array (\
[0] => ["6","1","2","5","3","4"]\
[1] => ["6","1","2","5","3","4"]\
[2] => ["6","1","2","5","3","4"]\
)\
';

Answer №3

To achieve the desired output, there are multiple approaches you can take:

One way is to utilize ES6 template literals:

var newfavz = `Array (

[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]

)
`;

Another option would be to use a backslash for line breaks:

var newfavz = 'Array (\n\
\n\
[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n\
[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n\
[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n\
\n)\
';

You can also concatenate strings to achieve the desired format:

var newfavz = 'Array (\n' +
'\n' +
'[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n' +
'[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n' +
'[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n' +
'\n' +
')\n';

The symbol \n represents a newline character in this context.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery UI accordion fails to function properly after refreshing the data

I am facing an issue with my HTML page where data is loaded dynamically into accordions. The accordion functionality is implemented inside a function, which is called at regular intervals to refresh the data. Initially, the accordion displays correctly, bu ...

I'm seeking clarification on the composition of Objects in Node.js

After running a console.log on a parameter from the callback function in the Node.js formidable package, here is the output of files: { fileUpload: [ PersistentFile { _events: [Object: null prototype], _eventsCount: 1, _maxListene ...

NPM encountered difficulties in resolving the dependency tree

I seem to be encountering a persistent issue that I cannot resolve on my own. My attempt to update webpack and webpack-cli in a project has been met with repeated errors of this nature: npm install webpack@latest --save-dev npm ERR! code ERESOLVE npm E ...

determining the quantity of dates

Is there a way to calculate the number of a specific day of the week occurring in a month using AngularJS? For example, how can I determine the count of Saturdays in a given month? Thank you. Here is the code snippet I have been working on: <!doctype ...

Issue with Angular translation when utilizing a dynamic key variable

I am currently developing a project with Angular Js and incorporating the Angular-translate module In a specific scenario, I encountered an issue where the translation key needed to be stored as a variable. To address this, I created an object within the ...

The function Slice() does not function properly when used with two-dimensional arrays

I have been attempting to duplicate a 2D array by value using the slice() method in order to prevent any changes made to the new array from impacting the original. Oddly enough, it seems that this approach is effective with a 1-dimensional array but not wi ...

When resizing the window in IE8, the function DIV offsetWidth/Width/innerWidth returns a value of zero

My page is filled with many elements, one of which is the following DIV: <div id="root"> .................. <div id="child1"> ............. </div> <div id="child2"> ............... </div> & ...

Verifying Initialization Before Destructing jQuery File Upload

I'm currently working with the blueimps jQuery file upload plugin and I need to delete all existing instances before creating new ones. The issue I'm running into is that I receive an error when attempting something like this: $('.upload&ap ...

Unable to see my Vue component within Laravel

My Vue component is not appearing on the screen and I am unable to identify the issue. I have checked my console for errors and I am using npm run hot Here is my app.js file: require('./bootstrap'); window.Vue = require('vue').default ...

Update the JavaScript and CSS files following an AJAX request with $.get

I am encountering an issue where my global CSS and JS files contain all the necessary definitions, but when I load new HTML blocks via AJAX $.get, these new elements do not receive the correct CSS/JS definitions. Is there a convenient way to refresh the ...

Sequential tests in the browser, not parallel

Currently, I am utilizing multiCapabilities for setting up multiple browsers. Is there a method to ensure that they run consecutively instead of concurrently? ...

Necessary to modify the camera's rotation axis within AFRAME

I have incorporated AFRAME into my metaverse application and am attempting to achieve a Third Person Perspective (TPP) for my avatars. I have implemented a rotate-with-camera component on my model so that the avatar rotates when the camera is rotated. Addi ...

What is the best way to reset the selected option in Vue.js when clicking on a (x) button?

Is there a way to create a function or button specifically for clearing select option fields? I attempted using <input type="reset" value="x" /> However, when I clear one field, all fields end up getting cleared. Should I provide my code that incl ...

Sending an Ajax request to a nearby address

I'm feeling a bit lost on how to achieve this task. I've been searching online, but it seems like my search terms may not have been quite right. My goal is to set up a RESTful api. $.ajax({ type: "POST", url: "https//my.url/", data: ...

"How can we trigger a re-render of a React component once a promise is fulfilled? Is there a way to prevent rendering until the

Having attempted to make updates to a functional component that interfaces with an azure-devops-ui/Filter, I've encountered a situation where I am utilizing the azure-devops-extension-sdk to handle async responses. This component is intended to be use ...

The pageSize in React's Material Table does not reflect dynamic updates

Currently, I am attempting to implement pagination for material table data using TablePagination. One issue I am facing is that the pageSize property, initially defined as a state variable, does not update when the selected pageSizeOptions change. Despite ...

Express.js Server Side Rendering - GET request for '/json/version/'

I have a running express server that pre-renders my react application. The routes file matches the HomeContainer to the base route / and all other routes match to the page not found. import HomeContainer from 'containers/home-container/home-container ...

Utilize Vue to call a method by providing its name as a string

When designing a navbar, I encountered the need to include a list of buttons. Some of these buttons should act as links, while others should call specific methods. For example, clicking on "Home" should direct the user to /home and clicking on "Log out" sh ...

Retrieve the data contained within a displayed embed tag that includes a src attribute

Can anyone provide guidance on how to retrieve the content of an embed tag using src attribute? I have an embed tag pointing to a custom page as src. I tried to use jquery to access the rendered content but I am not getting anything back. Any suggestions ...

Implementing NPM commands in Jenkins using shell scripting

Whenever I attempt to run the "npm" command, I encounter a syntax error. Users/Shared/Jenkins/Home/workspace/projectName/npm test ^^^^ SyntaxError: Unexpected identifier This is the Jenkins Build shel ...