简体   繁体   中英

Escaping characters in Javascript

function drawVisualization() {
    var query = new google.visualization.Query('http://spreadsheets.google.com/tq?key=XXXXXXX');
    query.setQuery('SELECT B, C, D, E, F, G, H where upper(B) like upper("%<?php echo $search; ?>%") or upper(D) like upper("%<?php echo $search; ?>%") or upper(E) like upper("%<?php echo $search; ?>%") or upper(F) like upper("%<?php echo $search; ?>%") order by G DESC label G "Data"');
    query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
    if (response.isError()) {
        alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
    }

    var data = response.getDataTable();

    var formatter = new google.visualization.PatternFormat(
        '<a href="{6}" target="_blank" onclick="var that=this;_gaq.push([\'_trackEvent\',\'Download archivio materiali\',\'{2}\',this.href]);setTimeout(function(){location.href=that.href;},200);return false;">{2}</a>');
    // Apply formatter and set the formatted value of the first column.
    formatter.format(data, [0, 1, 2, 3, 4, 5, 6], 2);

    var view = new google.visualization.DataView(data);
    view.setColumns([2, 0, 1, 4, 5]); // Create a view with the first column only.

    visualization = new google.visualization.Table(document.getElementById('table'));
    visualization.draw(view, {
        legend: 'bottom',
        allowHtml: true
    });

}

This is the smaller snippet interested by this question:

var formatter = new google.visualization.PatternFormat('<a href="{6}" target="_blank" onclick="var that=this;_gaq.push([\'_trackEvent\',\'Download archivio materiali\',\'{2}\',this.href]);setTimeout(function(){location.href=that.href;},200);return false;">{2}</a>');

It does work fine (it outputs a legit anchor with the correct data), except when in the title of the document (output by the variable {2} ) is present a character like a double quote ("). The anchor syntax would get screwed:

在此处输入图片说明

Do I need to escape/replace the double quotes using a function like replace? How can I do that?

JSFIDDLE

Try on the replacement for {2} something like:

var str = 'say: "blabla"';
str = str.replace(/"/g, '\\"');
console.log(str);

I've updated your fiddle code and have inserted:

// add a column with manipulated data
  var targetColIdx = data.getNumberOfColumns();          // will be the index of added column
  data.addColumn('string');
  var sourceColIdx = 2;                                  // get data from col 2
  var rowCount = data.getNumberOfRows();                 // save for loop condition
  var manipulated = "";
  for(var rowIndex=0; rowIndex<rowCount; rowIndex++)
  { manipulated = data.getValue(rowIndex, sourceColIdx); // get original
    manipulated = encodeURIComponent(manipulated);       // do some manipulation
    data.setCell(rowIndex, targetColIdx, manipulated);   // store in new column
  }

// modificated format: only use uri-encoded column in onclick attribute
  var formatter = new google.visualization.PatternFormat(
    '<a href="{6}" target="_blank" onclick="var that=this;_gaq.push([\'_trackEvent\',\'Download archivio materiali\',\'{'+targetColIdx+'}\',this.href]);setTimeout(function(){location.href=that.href;},200);return false;">{2}</a>');

I've not further investigated what will happen to the string in the click event handler. Maybe you will need another encoding or escaping as in the RegExp example above. You can adapt the line manipulated = encodeURIComponent(manipulated); to your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM