Подтвердить что ты не робот

JavaScript HERE-doc или другой механизм с большими котировками?

Есть ли удобный способ процитировать большой блок HTML, который имеет как одиночные, так и двойные кавычки в JavaScript?

Есть ли что-то вроде HERE-doc <<EOF, символа с несколькими кавычками """ или пользовательских разделителей q{}?

Любые творческие или изобретательные решения этой проблемы?

4b9b3361

Ответ 1

Некоторым людям это не нравится, поэтому будьте готовы к презрению и насмешкам, но один трюк заключается в том, чтобы сбросить ваш "большой блок вещей" в блок <script language="text">:

<script id='blockOfStuff' language="text">
  Hi this is random stuff
  <h1>Including HTML markup</h1>
  And quotes too, or as one man said, "These are quotes, but
  'these' are quotes too."
</script>

Джон Ресиг использовал эту технику (или эту мерзость, если хотите) на примерах своего шаблонного механизма.

Вы можете получить содержимое с помощью "innerText" или "innerHTML", если это необходимо, или через службы вашей любимой структуры.

edit — обратите внимание, что через jQuery (в отличие от того, что я сказал в комментарии ниже) .text() работает не, хотя я думаю, что это нужно. Вместо этого используйте .html().

Ответ 2

Не поддерживается.

Но поскольку мы говорим о способах его работы, здесь, который (по моему опыту):

<script type="text/javascript">  

    var name = "Mud";

    var str = "\
        My name is " + name + "\
        not to be confused with Bill\
        or Jack or Pete or Dennis\
        my name is " + name + " and it always been\
    ";

    alert("Les'n one: " + str);

</script>

Эти побочные эффекты сделают трюк. Просто убедитесь, что обратная косая черта - избегайте любых двойных кавычек в вашей строке, поскольку весь блок цитируется с ними.

Обратите внимание, что это не сохраняет символы новой строки, вам нужно вставить их вручную как "\n" перед завершающим косой чертой в каждой строке. С другой стороны, любой отступ пробела в начале каждой строки будет включен в выходной файл.

Действительно, это лучше всего работает, когда вам нужно объявить длинную многострочную строку в script (например, XML), а не так хорошо, когда вам нужно сохранить эту строку в точности так, как вы ее определяете.

Приветствия

Ответ 3

JavaScript не может этого сделать, но CoffeeScript, который является тонким слоем поверх JavaScript, может.

Следуйте по ссылке и прокрутите вниз до "Многострочные строки и Heredocs".

Ответ 4

Я помню, что некоторое время назад я видел умное решение, которое использовало многострочные комментарии в функции:

(function () {
   /*
      "This is an example of a multi-line string.  It really just a mult-line
      comment, and it wrapped in quote marks.  You might also notice the 
      apostrophe ;-)"; 
   */
});

Примечание: последний апостроф преднамеренно неверен; -P

Трюк заключается в вызове метода toString() и анализе многострочного комментария с использованием регулярного выражения. Умный, но очень похожий на предложение Уокти, немного мерзость.

На самом деле я не думал, что вопрос должен искать серьезный метод производства - моя собственная ошибка для перехода к выводам - ​​я не совсем уверен, почему вы не просто избежите соответствующего строкового литерала разделители. Как отметил Тим Даун в комментариях ниже, ECMAScript 3rd edition определяет toString(), поскольку функции зависят от реализации.

Для funsies я решил проверить совместимость браузера, и этот метод возможен в IE, Opera, Safari и Chrome, но не в Firefox, который не содержит комментариев в возвращаемой строке. http://jsfiddle.net/2yvXG/

Ответ 5

HereDoc для JavaScript

FuncToHereDoc ( "delemiter", невостребованная функция с комментариями HEREDOC)

function FuncToHereDoc(here,str) {
    var reobj = new RegExp("/\\*"+here+"\\n[\\s\\S]*?\\n"+here+"\\*/", "m");
    str = reobj.exec(str).toString();
    str = str.replace(new RegExp("/\\*"+here+"\\n",'m'),'').toString();
    return str.replace(new RegExp("\\n"+here+"\\*/",'m'),'').toString();
}

Использование:

FuncToHereDoc("HERE", MyHereDoc);

function MyHereDoc(){
/*HERE
<p>
This is written ing the HEREDOC, notice the multilines :D.
</p>
<p>
HERE
</p>
<p>
And Here
</p>
HERE*/
}

Ответ 6

ECMAscript 6, теперь стандарт, позволяет использовать обратные тики (ударная могила)   для цитирования многострочных литералов. К сожалению, это не   поддерживается в IE 11, поэтому его нельзя использовать на большинстве веб-сайтов.   (Кредит: Адам Кац, выше)

Пример:

var str=
`Line 1
Line 2`;

Ответ 7

Я действительно разработал вариант kludgy, аналогичный user742675, где вы поместили текст в div, а затем установите его видимость на none и потяните содержимое. Но просто указывать много HTML было недостаточно, поэтому я добавил функциональность, которая собрала все переменные, которые вы указали в script, поэтому, если у вас есть var a = 'Steve', любой экземпляр $a в тексте heredoc будет отображаться как "Стив".

<script type="text/javascript">
// set variables named andy and handy, which we can use as $andy and $handy in our text

var andy = "Fred Flintstone";
var handy = "Steve Austin";

function hereDoc(divid){
var obj = window; // gets an object containing all the variables
var str = document.getElementById(divid).innerHTML; // gets the HTML block
for(var i in obj){

/* the for loop recurses through all the objects in the page - remember strings are objects in Javascript */

if((typeof(obj[i])=="string")||(typeof(obj[i])=="number")){

/* Type of makes sure it only executes replacement for strings and numbers. The function worked without this test in Firefox and Safari, but threw errors on Opera until it was added. */

myregex = new RegExp('\\$'+i,"g");

/* To replace globally, you need to use a regular expression and use the "g" option, but within the string.replace() method, the regular expression is unquoted, so you can't use a variable in it directly. So we create it and assign it to a RegExp object that works in the string.replace() method. */

str = str.replace(myregex, obj[i]);

/* we replace instances of the variable name with a dollar sign before it with the variable value */
}
}
return str;

/* and when the loop is done, we return the processed text to be used however needed */

}

function gotoit(){

/* fill the "steve" div with the processed contents of the "randy" div. */

document.getElementById("steve").innerHTML = hereDoc("randy");
}

</script>

<a href="javascript:gotoit();">Run the script</a>
<div id="randy" style="display:none;">
The interesting thing about $andy is that he not nearly as popular with young kids as $handy.<br><br>

What I really find 'interesting' is that this "multiline" thing works as well as $handy bionic arm. <br><br>
</div>
<div id="steve"></div>

Ответ 8

Основываясь на предыдущих ответах и ​​различных вариантах использования, вот небольшой пример:

https://gist.github.com/lavoiesl/5880516

/*!
 * Extract a function comment, useful to have multiline string
 * @link https://gist.github.com/lavoiesl/5880516
 *
 * Don't forget to use /*! to avoid the comment being removed in minification 
 */

function extractFuncCommentString(func) {
  var matches = func.toString().match(/function\s*\(\)\s*\{\s*\/\*\!?\s*([\s\S]+?)\s*\*\/\s*\}/);
  if (!matches) return false;

  return matches[1];
}

var myString = extractFuncCommentString(function(){/*!
  <p>
    foo bar
  </p>
*/});

Ответ 9

Мне был интересен этот вопрос, потому что я хочу использовать javascript для добавления новой строки на экран редактирования (например, для нескольких телефонных номеров). (я мог бы использовать ajax для этого, но хотел бы избежать дополнительного запроса сервера.)

Мне нравится ответ Pointy об использовании тега для размещения блоков html, которые вы хотите использовать:

<script id='blockOfStuff'>
  Hi this is random stuff
  <h1>Including HTML markup</h1>
</script>

Но Firefox и Chrome жаловались на синтаксические ошибки, когда я это пробовал. Моим решением было изменить тег 'script' на div, скрыть его отображение от пользователей через css и перенести его в тело. например:.

<div style="display: none;" id="new_row_innerhtml">
  <td><a href="#" onclick="removeCurrentRow(this); return false;">Remove</a></td>
  <input type="hidden" name="id[]" value="new" />
  <td><input name="name[]" type="text" /></td>
</div>

That removed the syntax errors.

Here how I used that block:

I had an "Add" link that called the appendRow function:
<a href="#" onclick="appendRow(this); return false;">Add</a>

here the appendRow function:

function appendRow() {
  var tbl = document.getElementById('my_table');
  var row = tbl.insertRow(-1); // add to end of table
}

Ответ 10

// js heredoc - http://stackoverflow.com/a/32915549/466363
// a function with comment with eval-able string, use it just like regular string

function extractFuncCommentString(func,comments) {
  var matches = func.toString().match(/function\s*\(\)\s*\{\s*\/\*\!?\s*([\s\S]+?)\s*\*\/\s*\}/);
  if (!matches) return undefined;
  var str=matches[1];

   // i have made few flavors of comment removal add yours if you need something special, copy replacement lines from examples below, mix them
  if(comments===1 )
  {
   // keep comments, in order to keep comments  you need to convert /**/ to / * * / to be able to put them inside /**/ like /*    / * * /    */
   return (
    str
   .replace(/\/\s\*([\s\S]*?)\*\s\//g,"/*$1*/") //       change   / * text * /  to   /* text */ 
   )
  }
  else if(comments===2)
  {
   // keep comments and replace singleline comment to multiline comment
   return (
    str
   .replace(/\/\s\*([\s\S]*?)\*\s\//g,"/*$1*/") //       change   / * text * /  to   /* text */ 
   .replace(/\/\/(.*)/g,"/*$1*/")          //           change   //abc to  /*abc*/
   )
  }
  else if(comments===3)
  {
   // remove comments
   return (
      str
      .replace(/\/\s\*([\s\S]*?)\*\s\//g,"") //       match / * abc * /
      .replace(/\/\/(.*)/g,"")             // match //abc
     )
  }
  else if(comments===4)
  {
   // remove comments and trim and replace new lines with escape codes
   return (
      str
      .replace(/\/\s\*([\s\S]*?)\*\s\//g,"") //       match / * abc * /
      .replace(/\/\/(.*)/g,"")             // match //abc
      .trim() // after removing comments trim and:
      .replace(/\n/g,'\\n').replace(/\r/g,'\\r') // replace new lines with escape codes. allows further eval() of the string, you put in the comment function: a quoted text but with new lines
     )
  }
  else if(comments===5)
  {
   // keep comments comments and replace strings, might not suit when there are spaces or comments before and after quotes 
   // no comments allowed before quotes of the string
   // url html links
   return (
      str
      .replace(/\/\s\*([\s\S]*?)\*\s\//g,"/*$1*/") //       change   / * text * /  to   /* text */
      .replace(/\/\/(.*)/g,"/*$1*/")          //           change   //abc to  /*abc*/
      .trim() // trim space around quotes to not escape it and:
      .replace(/\n/g,'\\n').replace(/\r/g,'\\r') // replace new lines with escape codes. allows further eval() of the string, you put in the comment function: a quoted text but with new lines
     )
  }
  else if(comments===6)
  { // good for html with links
   // remove comments and trim and replace new lines with escape codes
   return (
      str
      .replace(/\/\s\*([\s\S]*?)\*\s\//g,"") //       match / * abc * /
      .trim() // after removing comments trim and:
      .replace(/\n/g,'\\n').replace(/\r/g,'\\r') // replace new lines with escape codes. allows further eval() of the string, you put in the comment function: a quoted text but with new lines
     )
  }
  else 
  return str
}

Пример

var week=true,b=123;
var q = eval(extractFuncCommentString(function(){/*!

// this is a comment     


'select 

/ * this
is a multiline 
comment * /

 a
,b  // this is a comment  
,c
from `table`
where b='+b+' and monthweek="'+(week?'w':'m')+'" 
//+' where  a=124
order by a asc
'
*/},4));

с кешем: - создайте простую функцию шаблона и сохраните функцию:

var cache={};
function myfunction(week,a){


    if(!cache.myfunction_sql1) eval('cache.myfunction_sql1=function(week,a){return ('+extractFuncCommentString(function(){/*!
'select 

/ * this
is a multiline 
comment * /

 a
,b  // this is a comment  
,c
from `table`
where b='+b+' and monthweek="'+(week?'w':'m')+'" 
//+' where  a=124
order by a asc

'*/},4)+')}');
    q=cache.myfunction_sql1(week,a);
    console.log(q)
}
myfunction(true,1234)

простой текст (не eval'd):

//var cache={};
function myfunction2(week,a){


    if(!cahce.myfunction_sql2) cahce.myfunction_sql2=extractFuncCommentString(function(){/*!

some multiline text
with <html>
and a link://to.url
and a / * comment * / 
*/},6);
    q=cahce.myfunction_sql2;
    console.log(q)
}

Ответ 11

Вот ваш ответ. В теле вашей страницы создаются промежутки или div, неважно, с каким уникальным идентификатором и помещаем весь текст, который вам нужен, со всеми кавычками, которые вы хотите. Сделайте стиль span или div "display: none, visibility: hidden;". Затем, когда вы хотите получить объект DOM из идентификатора и получить innerHTML, чтобы сделать то, что вы будете.