Shashank Jerri
Shashank Jerri

Reputation: 119

Uncaught SyntaxError: Unexpected token & in javascript django app

This is my function:

function convert_strings() {
var chart_labels = {{ chartlabels }};
var array_length = chart_labels.length;
for (var i = 0; i < array_length; i++) {
    chart_labels[i] = chart_labels[i].replace(/&#039;/g, "'")
    }
return chart_labels
}

This is my error: "Uncaught SyntaxError: Unexpected token &"

function convert_strings() {
var chart_labels = [&#39;CHENNAI LPG RO&#39;, &#39;KOCHI LPG RO&#39;, &#39;BANGALORE LPG RO&#39;, &#39;HUBLI LPG RO&#39;, &#39;MADURAI LPG RO&#39;, &#39;MANGLORE LPG RO&#39;];
var array_length = chart_labels.length;
for (var i = 0; i < array_length; i++) {
    chart_labels[i] = chart_labels[i].replace(/&#039;/g, "'")
    }
return chart_labels
}

Please advice what to do :)

Upvotes: 3

Views: 3593

Answers (3)

SachinDesai
SachinDesai

Reputation: 31

{{ chart_labels|safe }}

This would do it. No need to use .replace or jsonDump

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

In the view, you can convert the chartlabels to a JSON blob, for example with:

import json

def some_view(request):
    # ...
    context['chartlabels_json'] = json.dumps(context['chartlabels'])
    # ...
    return render(request, 'some_template.html', context)

In the template, we can then write the blob in an unescaped way:

function convert_strings() {
    return {{ chartlabels_json|safe }};
}

A more convenient way is however probably using the django-jsonify [PyPI] tool, and thus simply pass the charlabel through the jsonify filter.

Upvotes: 2

Ullas Hunka
Ullas Hunka

Reputation: 2211

Use the following, for more details on creating the regex for special characters follows this links javascript regex for special characters:

var str = '&#39;CHENNAI LPG RO&#39;'
console.log(str.replace(/\&\#39;/g, "'"));

Upvotes: 0

Related Questions