Unencode a list in javascript

Is there a way to convert escape codes back into the characters they represent in javascript? I am passing a list to a javascript file, and when I look at the source, instead of this

['/path/to/job/a', '/path/to/job/b', etc]

I am seeing this

['/path/to/job/a', '/path/to/job/b', etc]

I need the actual single quotes themselves for a jquery autocomplete call, so is there a way to convert back? I am passing the list to the javascript from a python/flask backend

return render_template('main_page.html', job_names = id_by_job.keys())

So in the javascript file, I am doing something like

$("#job_names").autocomplete({source : {{job_names}}});

Answers


Values interpolated into templates are always escaped for safe inclusion; that includes replacing quotes with HTML entities.

You want to convert your list to JSON here instead using the tojson filter, and mark the result as safe:

$("#job_names").autocomplete({source : {{ job_names|tojson_safe }}});

JSON is a subset of JavaScript; the result is directly readable as JavaScript, guaranteed to be properly escaped.


a neat trick is to use a temporary option:

var o=new Option();
o.innerHTML="'/path/to/job/a', '/path/to/job/b', etc"
alert(o.innerHTML); // shows: "'/path/to/job/a', '/path/to/job/b', etc"

you can also use a RegExp replace with a function callback:

"'/path/to/job/a', '/path/to/job/b', etc".replace(/&#(\d+);/g,
  function(j,a){
     return String.fromCharCode(a)
  }); // == "'/path/to/job/a', '/path/to/job/b', etc"

EDIT: i realized you probably want to handle arrays, and [].map() makes it easy to apply the above to an array:

['/path/to/job/a', '/path/to/job/b']
 .map(function(a){ return a.replace(/&#(\d+);/g, function(j,a){
      return String.fromCharCode(a)
  });
}); // == ["/path/to/job/a", "/path/to/job/b"]

Need Your Help

Menu Contols like the Office 2007 Ribbon

c# winforms office-2007 ribbon-control

Is there a way to my WinApp written in C# using Visual Studio 2008 have menu controls which look like on these We can fund in Office 2007.

get value and pass it to another activity from xml

android

I'm using the CustomizedList View code from this tutorial http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/