Error message: Handlebars failed to sanitize the string - SyntaxError: The string literal is missing

Currently, I am developing an application using Publii CMS, which utilizes Handlebars. Specifically, I am constructing a Vue app within the positions.hbs file. To create a JSON object, I am extracting a lengthy string from the CMS using Handlebars.

{{#getPostsByTags 30 "jobs" " "}}
  jobsData.push(
      {
        "title": "{{ title }}",
        "url": "{{ url }}",
        "mainTag": "{{ mainTag.name }}",
        "description": "{{ mainTag.description }}"
      }
    )
{{/getPostsByTags}}

The {{ mainTag.description }} snippet fetches the text stored in the CMS and triggers an error in the console.

SyntaxError: unterminated string literal

Upon inspection of line 45, it appears that there may be new lines or characters causing this error. The string on that line resembles the following:

https://i.sstatic.net/05ZEr.png

How can I sanitize or eliminate unwanted characters in Handlebars before passing them to the description value? I attempted to use JSON.stringify but without success.

 "description": "JSON.stringify({{ mainTag.description }})"

[Learn More]

What is the best approach for sanitizing this string? Should I resolve this issue within the CMS itself? The stored text only contains <p> tags. How can I address this problem? Subsequently, I pass this data to the Vue app with the complete code below.

<script>
    let jobsData = [];

    {{#getPostsByTags 30 "jobs" " "}}
      jobsData.push(
          {
            "title": "{{ title }}",
            "url": "{{ url }}",
            "mainTag": "{{ mainTag.name }}",
            "description": "{{ mainTag.description }}"
          }
        )
    {{/getPostsByTags}}

    window.onload = function () {
        var app = new Vue({
          delimiters: ['${', '}'],
          el: '#app',
          data: {
            jobs: jobsData
          },
          computed: {
            sectionTitlesWithJobs: function () {
              let tags = [];
              this.jobs.forEach(job=> {
                tags.push(job.mainTag)
              })

              tags = tags.filter((a, b) => tags.indexOf(a) === b)
              return tags.sort();
            }
          }
        });
    }
</script>

This is what the problematic string looks like:

"&lt;p&gt;The Product team conducts user research, creates user experience, and works closely with the internal and vendor technology teams to prototype, develop, and maintain evolving digital tools. The team also leads outreach, training and customer service for the &lt;/a href&#x3D;&quot;https://www1.nyc.gov/site/opportunity/portfolio/products.page&quot;&gt;products in its portfolio&lt;/a&gt;. The public-facing products include &lt;a href&#x3D;&quot;https://access.nyc.gov/&quot;&gt;ACCESS NYC&lt;/a&gt;,
        &lt;a href &quot;https://growingupnyc.cityofnewyork.us/&quot;&gt;Growing Up NYC&lt;/a&gt;, and &lt;a href&#x3D;&quot;https://growingupnyc.cityofnewyork.us/generationnyc/&quot;&gt;Generation NYC&lt;/a&gt; and their related APIs.&lt;/p&gt;&lt;p&gt;The Product team works closely integrated with other NYC Opportunity teams, including the development, design, and data teams. It also engages with other program and technology staff across City government. The team helps NYC Opportunity and our agency partners translate anti-poverty program and policy goals into digital strategies. The team also helps define how the City of New York uses modern, agile and user-centric approach to technology products, includin...

Answer №1

To eliminate line breaks from text, you can use the following code snippet:

mainTag.description.replace(/\n/g, '')

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

Issues with the functionality of AngularJS checkboxes

I'm currently working on a basic AngularJS project to improve my skills. Below are the code snippets I've included. I have two sets of JSON data. One set contains a list of grocery items, while the other set includes the items selected by the us ...

A JavaScript function that smoothly scrolls an element into view while considering any scrollable or positioned parent elements

I needed a function that could smoothly scroll a specific element into view with some intelligent behavior: If the element is a descendant of a scrollable element, I wanted the ancestor to be scrolled instead of the body. If the element is within a posit ...

The proxy feature in create-react-app does not function properly

When setting up my React app using create-react-app, I included the following in my package.json: After setting "proxy":"http://localhost:3001" in the package.json file to point to my API server running on port 3001, I encountered an issue where requests ...

Access information stored within nested JSON objects on a local server

After creating a test page, this is the structure that I have set up: <!DOCTYPE html> <html lang="en" class="no-js"> <head> <title>Get JSON Value</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/ ...

Console log is not displaying the JSON output

I am currently working on implementing a notification button feature for inactive articles on my blog. I want to ensure that the admin does not have to reload the page to see any new submitted inactive articles. To achieve this, I am looking to use Ajax, a ...

Locate and substitute text, language equivalency

I'm encountering issues with finding and replacing words in PHP files, especially when dealing with a large number of them. I'm considering using javascript/jQuery as an alternative solution. I want to create a table mapping word_to_replace to ne ...

Refresh the list items in a v-for loop once the promise has successfully resolved

I am working on a scenario where I have a list that iterates through an array of objects, generating list items that are dependent on the current object. As part of this process, a calculation needs to be performed with the object as a parameter, which in ...

Guide to setting up an object array in JavaScript with unique child elements and no duplicate values

I have an array that looks like this: sampleArray = ["x", "y", "z". "a.b", "a.b.c", "a.b.d", "a.e.f", "a.e.g"] However, I am aiming to transform it into the following structure, or something similar to it: newArray: [ { "x": [] }, ...

What's a way to pass a PHP variable directly to Javascript without using AJAX?

In my setup, I've implemented a JavaScript code that validates and sends the 'artwork' file to a PHP script on my server. This PHP script also performs its own checks for redundancy before writing the file to /uploads directory. The challen ...

Prevent the Vue page from loading until the data has been fetched successfully

I'm in the process of finding a way to prevent my page from loading until my fetch task is completed. I'm facing some issues that need to be addressed: I have to re-fetch the data each time because I can't reuse the same data. (Changing vie ...

Can you explain the functionality of $scope.$apply()?

Lately, I've been incorporating $scope.$apply() into my Angular applications to refresh the bindings for my models when new data is received via websockets. It seems to be effective, but I'm curious about its actual functionality and why it' ...

Knockout Js' observable objects are not updating the UI to reflect changes in the data

Displayed below is the view modal where an ajax response is obtained and loaded into the observable value. var userManagementVM = { responseSetUpData: ko.observable({ userList: ko.observable(), userListViewModel: ko.observableArray(), ...

Dynamic Checkbox Functionality in REACT

Motivation: My goal is to generate multiple rows with a variable number of checkboxes that will be managed by a useState hook. Challenge: The page freezes or displays constant loading, with no content visible. There are no console logs, and even the debug ...

Showing information in Angular without using $scope

When working with Angular and angular UI-Router, my goal is to display content without relying on $scope. In my mainController, using directives like ng-repeat is no problem. However, I am struggling to access information from my postsController. Despite ...

Having trouble with a lengthy formula in your Google Sheets Apps Script function? You may encounter an error like `SyntaxError: missing ) after argument list line: 14 file: new line.gs`. Let

The Apps Script function being discussed: function insertNewRow() { var ss = SpreadsheetApp.openById("redactedforprivacy"); var sheet = ss.getSheetByName("Main"); sheet.insertRowBefore(2); var date = new Date(); var month = date.getMonth() + 1 ...

Updating ViewModel and refreshing the view following an AJAX request

I need assistance in creating a table where each row has a child row serving as a details section. This details section should display a log history and allow users to input new logs. Upon adding a new log by clicking the "Add" button, the log history shou ...

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...

Incorporating an anchor into dynamically created URLs

Despite my efforts to find a similar example to solve my issue, I am struggling to make it work. I apologize if this problem sounds like others. Currently, I am utilizing Terminal Four's Site Manager CMS system for constructing my websites. This tool ...

Is it possible for Javascript to manipulate the DOM of an Ajax text/html response?

My goal is to implement Ajax to retrieve an HTML page and extract a specific div by its ID, then insert that div into the current page. This involves loading a second page via Ajax, extracting the specified div from the response, and placing it within th ...

Turn off eslint for Vue.js

Currently, I'm following a tutorial on how to complete a project. However, I have encountered an error related to ESLint: > Failed to compile. ./src/App.vue Module Error (from ./node_modules/eslint-loader/index.js): C:\Users\romul&bsol ...