如何将多行字符串文字分配给变量?

发布于 2024-11-03 12:40:06 字数 120 浏览 6 评论 0原文

如何将带有多行字符串的 Ruby 代码转换为 JavaScript?

text = <<"HERE"
This
Is
A
Multiline
String
HERE

How do I convert this Ruby code with a multiline string into JavaScript?

text = <<"HERE"
This
Is
A
Multiline
String
HERE

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

慵挽 2024-11-10 12:40:07

ES6 允许您使用反引号在多行上指定一个字符串。它称为模板文字。像这样:

var multilineString = `One line of text
    second line of text
    third line of text
    fourth line of text`;

在 NodeJS 中可以使用反引号,并且 Chrome、Firefox、Edge、Safari 和 Opera 都支持它。

https://developer.mozilla.org/en-US/docs /Web/JavaScript/Reference/Template_literals

ES6 allows you to use a backtick to specify a string on multiple lines. It's called a Template Literal. Like this:

var multilineString = `One line of text
    second line of text
    third line of text
    fourth line of text`;

Using the backtick works in NodeJS, and it's supported by Chrome, Firefox, Edge, Safari, and Opera.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

眼眸 2024-11-10 12:40:07

您可以使用标记模板来确保获得所需的输出。

例如:

// Merging multiple whitespaces and trimming the output

const t = (strings) => { return strings.map((s) => s.replace(/\s+/g, ' ')).join("").trim() }
console.log(t`
  This
  Is
  A
  Multiline
  String
`);
// Output: 'This Is A Multiline String'

// Similar but keeping whitespaces:

const tW = (strings) => { return strings.map((s) => s.replace(/\s+/g, '\n')).join("").trim() }
console.log(tW`
  This
  Is
  A
  Multiline
  String
`);
// Output: 'This\nIs\nA\nMultiline\nString'

You can use tagged templates to make sure you get the desired output.

For example:

// Merging multiple whitespaces and trimming the output

const t = (strings) => { return strings.map((s) => s.replace(/\s+/g, ' ')).join("").trim() }
console.log(t`
  This
  Is
  A
  Multiline
  String
`);
// Output: 'This Is A Multiline String'

// Similar but keeping whitespaces:

const tW = (strings) => { return strings.map((s) => s.replace(/\s+/g, '\n')).join("").trim() }
console.log(tW`
  This
  Is
  A
  Multiline
  String
`);
// Output: 'This\nIs\nA\nMultiline\nString'
北渚 2024-11-10 12:40:07

另请注意,当在每行末尾使用正向反斜杠将字符串扩展到多行时,正向反斜杠后的任何额外字符(主要是空格、制表符和错误添加的注释)都会导致意外的字符错误,我花了一个小时才找到出去

var string = "line1\  // comment, space or tabs here raise error
line2";

Also do note that, when extending string over multiple lines using forward backslash at end of each line, any extra characters (mostly spaces, tabs and comments added by mistake) after forward backslash will cause unexpected character error, which i took an hour to find out

var string = "line1\  // comment, space or tabs here raise error
line2";
我纯我任性 2024-11-10 12:40:07

出于对互联网的热爱,请使用字符串连接并选择不使用 ES6 解决方案。 ES6 并未得到全面支持,就像 CSS3 一样,并且某些浏览器适应 CSS3 运动的速度很慢。使用简单的 JavaScript,您的最终用户会感谢您。

示例:

var str =“这个世界既不是平的也不是圆的。”+
“一旦失去,就会被找到”;

Please for the love of the internet use string concatenation and opt not to use ES6 solutions for this. ES6 is NOT supported all across the board, much like CSS3 and certain browsers being slow to adapt to the CSS3 movement. Use plain ol' JavaScript, your end users will thank you.

Example:

var str = "This world is neither flat nor round. "+
"Once was lost will be found";

套路撩心 2024-11-10 12:40:07

带变量的多行字符串

var x = 1
string = string + `<label class="container">
                       <p>${x}</p>
                   </label>`;

Multiline string with variables

var x = 1
string = string + `<label class="container">
                       <p>${x}</p>
                   </label>`;
蓝眼泪 2024-11-10 12:40:06

更新:

ECMAScript 6 (ES6) 引入了一种新的文字类型,即 模板文字。它们有很多功能,变量插值等,但对于这个问题最重要的是,它们可以是多行的。

模板文字由反引号分隔:(

var html = `
  <div>
    <span>Some HTML here</span>
  </div>
`;

注意:我不提倡在字符串中使用 HTML)

浏览器支持还可以,但您可以使用转译器来提高兼容性。


ES5 原始答案:

Javascript 没有此处文档语法。但是,您可以转义文字换行符,它很接近:

"foo \
bar"

Update:

ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.

A template literal is delimited by backticks:

var html = `
  <div>
    <span>Some HTML here</span>
  </div>
`;

(Note: I'm not advocating to use HTML in strings)

Browser support is OK, but you can use transpilers to be more compatible.


Original ES5 answer:

Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:

"foo \
bar"
唐婉 2024-11-10 12:40:06

ES6 更新:

正如第一个答案提到的,使用 ES6/Babel,您现在只需使用反引号即可创建多行字符串:

const htmlString = `Say hello to 
multi-line
strings!`;

插值变量是一项流行的新功能,带有反引号分隔字符串:

const htmlString = `${user.name} liked your post about strings`;

这只是转换为串联:

user.name + ' liked your post about strings'

ES5 原始答案:

Google 的 JavaScript 样式指南建议改用字符串连接转义换行符:

不要这样做:

var myString = '一段相当长的英文文本字符串,一条错误消息\
                实际上,这只是一直持续下去——一个错误\
                让劲量兔子脸红的消息(直接通过\
                那些施瓦辛格色调)!我当时在哪儿?哦是的, \
                你有一个错误,所有无关的空格都是 \
                只是肉汁。祝你今天过得愉快。';

每行开头的空格在编译时无法安全地去除;斜杠后面的空格会导致棘手的错误;虽然大多数脚本引擎都支持这一点,但它不是 ECMAScript 的一部分。

改用字符串连接:

var myString = '一串相当长的英文文本,一条错误消息' +
               '实际上,这只是一直持续下去——一个错误' +
               '让劲量兔子脸红的消息(直接通过 ' +
               '那些施瓦辛格的色调)!我当时在哪儿?哦,是的,'+
               '你遇到了一个错误,所有无关的空格都是 ' +
               '只是肉汁。祝你今天过得愉快。';

ES6 Update:

As the first answer mentions, with ES6/Babel, you can now create multi-line strings simply by using backticks:

const htmlString = `Say hello to 
multi-line
strings!`;

Interpolating variables is a popular new feature that comes with back-tick delimited strings:

const htmlString = `${user.name} liked your post about strings`;

This just transpiles down to concatenation:

user.name + ' liked your post about strings'

Original ES5 answer:

Google's JavaScript style guide recommends to use string concatenation instead of escaping newlines:

Do not do this:

var myString = 'A rather long string of English text, an error message \
                actually that just keeps going and going -- an error \
                message to make the Energizer bunny blush (right through \
                those Schwarzenegger shades)! Where was I? Oh yes, \
                you\'ve got an error and all the extraneous whitespace is \
                just gravy.  Have a nice day.';

The whitespace at the beginning of each line can't be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript.

Use string concatenation instead:

var myString = 'A rather long string of English text, an error message ' +
               'actually that just keeps going and going -- an error ' +
               'message to make the Energizer bunny blush (right through ' +
               'those Schwarzenegger shades)! Where was I? Oh yes, ' +
               'you\'ve got an error and all the extraneous whitespace is ' +
               'just gravy.  Have a nice day.';
生寂 2024-11-10 12:40:06

模式 text = <<"HERE" This Is A Multiline String HERE 在 js 中不可用(我记得在我美好的 Perl 岁月里经常使用它)。

为了对复杂或长的多行字符串进行监督,我有时会使用数组模式:

var myString = 
   ['<div id="someId">',
    'some content<br />',
    '<a href="#someRef">someRefTxt</a>',
    '</div>'
   ].join('\n');

或已经显示的匿名模式(转义换行符),这可能是代码中的一个丑陋的块:

    var myString = 
       '<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';

这是另一个奇怪但有效的“技巧”1

var myString = (function () {/*
   <div id="someId">
     some content<br />
     <a href="#someRef">someRefTxt</a>
    </div>        
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

外部编辑:jsfiddle

ES20xx 支持使用 模板字符串:

let str = `This is a text
    with multiple lines.
    Escapes are interpreted,
    \n is a newline.`;
let str = String.raw`This is a text
    with multiple lines.
    Escapes are not interpreted,
    \n is not a newline.`;

1 注意:在缩小/混淆代码后,这将丢失

the pattern text = <<"HERE" This Is A Multiline String HERE is not available in js (I remember using it much in my good old Perl days).

To keep oversight with complex or long multiline strings I sometimes use an array pattern:

var myString = 
   ['<div id="someId">',
    'some content<br />',
    '<a href="#someRef">someRefTxt</a>',
    '</div>'
   ].join('\n');

or the pattern anonymous already showed (escape newline), which can be an ugly block in your code:

    var myString = 
       '<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';

Here's another weird but working 'trick'1:

var myString = (function () {/*
   <div id="someId">
     some content<br />
     <a href="#someRef">someRefTxt</a>
    </div>        
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

external edit: jsfiddle

ES20xx supports spanning strings over multiple lines using template strings:

let str = `This is a text
    with multiple lines.
    Escapes are interpreted,
    \n is a newline.`;
let str = String.raw`This is a text
    with multiple lines.
    Escapes are not interpreted,
    \n is not a newline.`;

1 Note: this will be lost after minifying/obfuscating your code

清晨说晚安 2024-11-10 12:40:06

您可以在纯 JavaScript 中使用多行字符串。

此方法基于函数的序列化,该函数定义为依赖于实现 。它确实可以在大多数浏览器中工作(见下文),但不能保证它将来仍然可以工作,所以不要依赖它。

使用以下功能:

function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*!?/, '').
      replace(/\*\/[^\/]+$/, '');
}

您可以在此处拥有这样的文档:

var tennysonQuote = hereDoc(function() {/*!
  Theirs not to make reply,
  Theirs not to reason why,
  Theirs but to do and die
*/});

该方法已在以下浏览器中成功测试(未提及 = 未测试):

  • IE 4 - 10
  • Opera 9.50 - 12(不在 9- 中)
  • Safari 4 - 6 (不在 3- 中)
  • Chrome 1 - 45
  • Firefox 17 - 21 (16- 中没有)
  • Rekonq 0.7.0 - 0.8.0
  • Konqueror 4.7.4 不支持

不过,请小心您的压缩器。它往往会删除评论。对于 YUI 压缩器,以 /*! 开头的注释(例如我使用的那个)将被保留。

我认为真正的解决方案是使用 CoffeeScript

ES6 更新:您可以使用反引号,而不是创建带有注释的函数并在注释上运行 toString。正则表达式需要更新为仅删除空格。您还可以有一个字符串原型方法来执行此操作:

let foo = `
  bar loves cake
  baz loves beer
  beer loves people
`.removeIndentation()

有人应该编写这个 .removeIndentation 字符串方法...;)

You can have multiline strings in pure JavaScript.

This method is based on the serialization of functions, which is defined to be implementation-dependent. It does work in the most browsers (see below), but there's no guarantee that it will still work in the future, so do not rely on it.

Using the following function:

function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*!?/, '').
      replace(/\*\/[^\/]+$/, '');
}

You can have here-documents like this:

var tennysonQuote = hereDoc(function() {/*!
  Theirs not to make reply,
  Theirs not to reason why,
  Theirs but to do and die
*/});

The method has successfully been tested in the following browsers (not mentioned = not tested):

  • IE 4 - 10
  • Opera 9.50 - 12 (not in 9-)
  • Safari 4 - 6 (not in 3-)
  • Chrome 1 - 45
  • Firefox 17 - 21 (not in 16-)
  • Rekonq 0.7.0 - 0.8.0
  • Not supported in Konqueror 4.7.4

Be careful with your minifier, though. It tends to remove comments. For the YUI compressor, a comment starting with /*! (like the one I used) will be preserved.

I think a real solution would be to use CoffeeScript.

ES6 UPDATE: You could use backtick instead of creating a function with a comment and running toString on the comment. The regex would need to be updated to only strip spaces. You could also have a string prototype method for doing this:

let foo = `
  bar loves cake
  baz loves beer
  beer loves people
`.removeIndentation()

Someone should write this .removeIndentation string method... ;)

够钟 2024-11-10 12:40:06

你可以这样做...

var string = 'This is\n' +
'a multiline\n' + 
'string';

You can do this...

var string = 'This is\n' +
'a multiline\n' + 
'string';
双手揣兜 2024-11-10 12:40:06

我想出了这个非常吉米操纵的多线绳索方法。由于将函数转换为字符串还会返回函数内的任何注释,因此您可以使用多行注释 /**/ 将注释用作字符串。你只需要把末端剪掉就可以了。

var myString = function(){/*
    This is some
    awesome multi-lined
    string using a comment 
    inside a function 
    returned as a string.
    Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)

alert(myString)

I came up with this very jimmy rigged method of a multi lined string. Since converting a function into a string also returns any comments inside the function you can use the comments as your string using a multilined comment /**/. You just have to trim off the ends and you have your string.

var myString = function(){/*
    This is some
    awesome multi-lined
    string using a comment 
    inside a function 
    returned as a string.
    Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)

alert(myString)
拧巴小姐 2024-11-10 12:40:06

我很惊讶我没有看到这个,因为它在我测试过的任何地方都有效,并且对于例如模板非常有用:

<script type="bogus" id="multi">
    My
    multiline
    string
</script>
<script>
    alert($('#multi').html());
</script>

有人知道有 HTML 但它不起作用的环境吗?

I'm surprised I didn't see this, because it works everywhere I've tested it and is very useful for e.g. templates:

<script type="bogus" id="multi">
    My
    multiline
    string
</script>
<script>
    alert($('#multi').html());
</script>

Does anybody know of an environment where there is HTML but it doesn't work?

锦上情书 2024-11-10 12:40:06

我通过输出一个 div,将其隐藏,并在需要时通过 jQuery 调用 div id 来解决这个问题。

例如

<div id="UniqueID" style="display:none;">
     Strings
     On
     Multiple
     Lines
     Here
</div>

,当我需要获取字符串时,我只需使用以下 jQuery:

$('#UniqueID').html();

它会在多行上返回我的文本。如果我打电话,

alert($('#UniqueID').html());

我会得到:

在此处输入图像描述

I solved this by outputting a div, making it hidden, and calling the div id by jQuery when I needed it.

e.g.

<div id="UniqueID" style="display:none;">
     Strings
     On
     Multiple
     Lines
     Here
</div>

Then when I need to get the string, I just use the following jQuery:

$('#UniqueID').html();

Which returns my text on multiple lines. If I call

alert($('#UniqueID').html());

I get:

enter image description here

温柔嚣张 2024-11-10 12:40:06

有多种方法可以实现这一目标

1。斜杠连接

  var MultiLine=  '1\
    2\
    3\
    4\
    5\
    6\
    7\
    8\
    9';

2.常规连接

var MultiLine = '1'
+'2'
+'3'
+'4'
+'5';

3.数组连接连接

var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');

从性能角度来看,斜线连接(第一个)是最快的。

请参阅此测试用例,了解有关性能的更多详细信息

更新:

ES2015,我们可以利用它的模板字符串功能。有了它,我们只需要使用反引号来创建多行字符串

示例:

 `<h1>{{title}}</h1>
  <h2>{{hero.name}} details!</h2>
  <div><label>id: </label>{{hero.id}}</div>
  <div><label>name: </label>{{hero.name}}</div>
  `

There are multiple ways to achieve this

1. Slash concatenation

  var MultiLine=  '1\
    2\
    3\
    4\
    5\
    6\
    7\
    8\
    9';

2. regular concatenation

var MultiLine = '1'
+'2'
+'3'
+'4'
+'5';

3. Array Join concatenation

var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');

Performance wise, Slash concatenation (first one) is the fastest.

Refer this test case for more details regarding the performance

Update:

With the ES2015, we can take advantage of its Template strings feature. With it, we just need to use back-ticks for creating multi line strings

Example:

 `<h1>{{title}}</h1>
  <h2>{{hero.name}} details!</h2>
  <div><label>id: </label>{{hero.id}}</div>
  <div><label>name: </label>{{hero.name}}</div>
  `
妖妓 2024-11-10 12:40:06

使用脚本标签:

  • 将包含多行文本的 块添加到 head 标签中;
  • 按原样获取多行文本...(注意文本编码:UTF-8、ASCII)

    <前><代码><脚本>;

    // 纯 JavaScript
    var text = document.getElementById("mySoapMessage").innerHTML ;

    // 为了安全起见,使用 JQuery 的文档
    $(文档).ready(函数() {

    var text = $("#mySoapMessage").html();

    });

    <脚本 id="mySoapMessage" type="text/plain">


    >

    <类型:getConvocadosElement>
    ...


    //呃-哦,JavaScript 注释... SOAP 请求将失败

Using script tags:

  • add a <script>...</script> block containing your multiline text into head tag;
  • get your multiline text as is... (watch out for text encoding: UTF-8, ASCII)

    <script>
    
        // pure javascript
        var text = document.getElementById("mySoapMessage").innerHTML ;
    
        // using JQuery's document ready for safety
        $(document).ready(function() {
    
            var text = $("#mySoapMessage").html(); 
    
        });
    
    </script>
    
    <script id="mySoapMessage" type="text/plain">
    
        <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="...">
           <soapenv:Header/>
           <soapenv:Body>
              <typ:getConvocadosElement>
                 ...
              </typ:getConvocadosElement>
           </soapenv:Body>
        </soapenv:Envelope>
    
        <!-- this comment will be present on your string -->
        //uh-oh, javascript comments...  SOAP request will fail 
    
    
    </script>
    
旧故 2024-11-10 12:40:06

在 JavaScript 中打印多行字符串的一种简单方法是使用由反引号 (``) 表示的模板文字(模板字符串)。您还可以在模板字符串中使用变量(` name is ${value} `)

您还可以

const value = `multiline`
const text = `This is a
${value}
string in js`;
console.log(text);

A simple way to print multiline strings in JavaScript is by using template literals(template strings) denoted by backticks (` `). you can also use variables inside a template string-like (` name is ${value} `)

You can also

const value = `multiline`
const text = `This is a
${value}
string in js`;
console.log(text);

遗失的美好 2024-11-10 12:40:06

我喜欢这种语法和缩进:(

string = 'my long string...\n'
       + 'continue here\n'
       + 'and here.';

但实际上不能被视为多行字符串)

I like this syntax and indendation:

string = 'my long string...\n'
       + 'continue here\n'
       + 'and here.';

(but actually can't be considered as multiline string)

不一样的天空 2024-11-10 12:40:06

反对者:此代码仅供参考。

此功能已在 Mac 上的 Fx 19 和 Chrome 24 中进行了测试

DEMO

var new_comment; /*<<<EOF 
    <li class="photobooth-comment">
       <span class="username">
          <a href="#">You</a>:
       </span>
       <span class="comment-text">
          $text
       </span> 
       @<span class="comment-time">
          2d
       </span> ago
    </li>
EOF*/
// note the script tag here is hardcoded as the FIRST tag 
new_comment=document.currentScript.innerHTML.split("EOF")[1]; 
document.querySelector("ul").innerHTML=new_comment.replace('$text','This is a dynamically created text');
<ul></ul>

Downvoters: This code is supplied for information only.

This has been tested in Fx 19 and Chrome 24 on Mac

DEMO

var new_comment; /*<<<EOF 
    <li class="photobooth-comment">
       <span class="username">
          <a href="#">You</a>:
       </span>
       <span class="comment-text">
          $text
       </span> 
       @<span class="comment-time">
          2d
       </span> ago
    </li>
EOF*/
// note the script tag here is hardcoded as the FIRST tag 
new_comment=document.currentScript.innerHTML.split("EOF")[1]; 
document.querySelector("ul").innerHTML=new_comment.replace('$text','This is a dynamically created text');
<ul></ul>

晒暮凉 2024-11-10 12:40:06

有一个让它变得美丽的库:

https://github.com/sindresorhus/multiline

之前

var str = '' +
'<!doctype html>' +
'<html>' +
'   <body>' +
'       <h1>❤ unicorns</h1>' +
'   </body>' +
'</html>' +
'';

之后

var str = multiline(function(){/*
<!doctype html>
<html>
    <body>
        <h1>❤ unicorns</h1>
    </body>
</html>
*/});

There's this library that makes it beautiful:

https://github.com/sindresorhus/multiline

Before

var str = '' +
'<!doctype html>' +
'<html>' +
'   <body>' +
'       <h1>❤ unicorns</h1>' +
'   </body>' +
'</html>' +
'';

After

var str = multiline(function(){/*
<!doctype html>
<html>
    <body>
        <h1>❤ unicorns</h1>
    </body>
</html>
*/});
疏忽 2024-11-10 12:40:06

在这里找到了很多过度设计的答案。
我认为两个最好的答案是:

1:

 let str = `Multiline string.
            foo.
            bar.`

最终记录:

Multiline string.
           foo.
           bar.  

2:

let str = `Multiline string.
foo.
bar.`

正确记录它,但如果 str 嵌套在函数/对象等内部,则在脚本文件中很难看...:

Multiline string.
foo.
bar.

我使用正则表达式记录的非常简单的答案str 正确:

let str = `Multiline string.
           foo.
           bar.`.replace(/\n +/g, '\n');

请注意,这不是完美的解决方案,但如果您确定新行 (\n) 之后至少会出现一个空格(+ 表示至少出现一次),则它可以工作。它还适用于 *(零个或多个)。

您可以更明确地使用 {n,} 表示至少出现 n 次。

Found a lot of over engineered answers here.
The two best answers in my opinion were:

1:

 let str = `Multiline string.
            foo.
            bar.`

which eventually logs:

Multiline string.
           foo.
           bar.  

2:

let str = `Multiline string.
foo.
bar.`

That logs it correctly but it's ugly in the script file if str is nested inside functions / objects etc...:

Multiline string.
foo.
bar.

My really simple answer with regex which logs the str correctly:

let str = `Multiline string.
           foo.
           bar.`.replace(/\n +/g, '\n');

Please note that it is not the perfect solution but it works if you are sure that after the new line (\n) at least one space will come (+ means at least one occurrence). It also will work with * (zero or more).

You can be more explicit and use {n,} which means at least n occurrences.

肥爪爪 2024-11-10 12:40:06

javascript 中的等效内容是:

var text = `
This
Is
A
Multiline
String
`;

这是规范。请参阅此页面底部的浏览器支持。这里还有一些示例

The equivalent in javascript is:

var text = `
This
Is
A
Multiline
String
`;

Here's the specification. See browser support at the bottom of this page. Here are some examples too.

相权↑美人 2024-11-10 12:40:06

精确的

Ruby 产生“This\nIs\nA\nMultiline\nString\n” -下面的 JS 产生完全相同的字符串

text = `This
Is
A
Multiline
String
`

// TEST
console.log(JSON.stringify(text));
console.log(text);

这是对Lonnie最佳答案的改进,因为他的答案中的换行符与ruby输出中的位置不完全相同

Exact

Ruby produce: "This\nIs\nA\nMultiline\nString\n" - below JS produce exact same string

text = `This
Is
A
Multiline
String
`

// TEST
console.log(JSON.stringify(text));
console.log(text);

This is improvement to Lonnie Best answer because new-line characters in his answer are not exactly the same positions as in ruby output

弃爱 2024-11-10 12:40:06

这适用于 IE、Safari、Chrome 和 Firefox:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class="crazy_idea" thorn_in_my_side='<table  border="0">
                        <tr>
                            <td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
                        </tr>
                    </table>'></div>
<script type="text/javascript">
    alert($(".crazy_idea").attr("thorn_in_my_side"));
</script>

This works in IE, Safari, Chrome and Firefox:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class="crazy_idea" thorn_in_my_side='<table  border="0">
                        <tr>
                            <td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
                        </tr>
                    </table>'></div>
<script type="text/javascript">
    alert($(".crazy_idea").attr("thorn_in_my_side"));
</script>
笨笨の傻瓜 2024-11-10 12:40:06

总而言之,我尝试了用户 javascript 编程(Opera 11.01)中列出的两种方法:

所以我推荐 Opera 用户 JS 用户的工作方法。与作者所说的不同:

它不适用于 Firefox 或 Opera;仅适用于 IE、Chrome 和 Safari。

它确实可以在 Opera 11 中工作。至少在用户 JS 脚本中是这样。太糟糕了,我无法对个别答案发表评论或对答案进行投票,我会立即这样做。如果可能的话,请有更高权限的人帮我做。

to sum up, I have tried 2 approaches listed here in user javascript programming (Opera 11.01):

So I recommend the working approach for Opera user JS users. Unlike what the author was saying:

It doesn't work on firefox or opera; only on IE, chrome and safari.

It DOES work in Opera 11. At least in user JS scripts. Too bad I can't comment on individual answers or upvote the answer, I'd do it immediately. If possible, someone with higher privileges please do it for me.

烟凡古楼 2024-11-10 12:40:06

我对 https://stackoverflow.com/a/15558082/80404 的扩展。
它需要以 /*! 形式的注释。任何多行注释 */ 其中符号 !用于防止缩小删除(至少对于 YUI 压缩器)

Function.prototype.extractComment = function() {
    var startComment = "/*!";
    var endComment = "*/";
    var str = this.toString();

    var start = str.indexOf(startComment);
    var end = str.lastIndexOf(endComment);

    return str.slice(start + startComment.length, -(str.length - end));
};

示例:

var tmpl = function() { /*!
 <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
    </ul>
 </div>
*/}.extractComment();

My extension to https://stackoverflow.com/a/15558082/80404.
It expects comment in a form /*! any multiline comment */ where symbol ! is used to prevent removing by minification (at least for YUI compressor)

Function.prototype.extractComment = function() {
    var startComment = "/*!";
    var endComment = "*/";
    var str = this.toString();

    var start = str.indexOf(startComment);
    var end = str.lastIndexOf(endComment);

    return str.slice(start + startComment.length, -(str.length - end));
};

Example:

var tmpl = function() { /*!
 <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
    </ul>
 </div>
*/}.extractComment();
霞映澄塘 2024-11-10 12:40:06

2015年更新:现在已经六年了:大多数人都使用模块加载器,并且主要模块系统都有加载模板的方法。它不是内联的,但最常见的多行字符串类型是模板,并且模板通常应该远离 JS

require.js:“需要文本”。

使用 require.js 'text' 插件,并在 template.html

var template = require('text!template.html')

NPM/browserify:“brfs”模块

Browserify 使用“brfs”模块加载文本文件。这实际上会将您的模板构建到捆绑的 HTML 中。

var fs = require("fs");
var template = fs.readFileSync(template.html', 'utf8');

简单的。

Updated for 2015: it's six years later now: most people use a module loader, and the main module systems each have ways of loading templates. It's not inline, but the most common type of multiline string are templates, and templates should generally be kept out of JS anyway.

require.js: 'require text'.

Using require.js 'text' plugin, with a multiline template in template.html

var template = require('text!template.html')

NPM/browserify: the 'brfs' module

Browserify uses a 'brfs' module to load text files. This will actually build your template into your bundled HTML.

var fs = require("fs");
var template = fs.readFileSync(template.html', 'utf8');

Easy.

魄砕の薆 2024-11-10 12:40:06

如果您愿意使用转义换行符,它们可以很好地使用。 它看起来像一个带有页面边框的文档

在此处输入图像描述

If you're willing to use the escaped newlines, they can be used nicely. It looks like a document with a page border.

enter image description here

美人骨 2024-11-10 12:40:06

在 JavaScript 中创建多行字符串的最简单方法是使用反引号 (``)。这允许您创建多行字符串,您可以在其中插入带有 ${variableName} 的变量。

例子:

let name = 'Willem'; 
let age = 26;

let multilineString = `
my name is: ${name}

my age is: ${age}
`;

console.log(multilineString);

兼容性:

  • 它是在 ES6//es2015 中引入的
  • ,现在所有主要浏览器供应商(除了 Internet Explorer)都原生支持它

在此处检查 Mozilla 文档中的确切兼容性

Easiest way to make multiline strings in Javascrips is with the use of backticks ( `` ). This allows you to create multiline strings in which you can insert variables with ${variableName}.

Example:

let name = 'Willem'; 
let age = 26;

let multilineString = `
my name is: ${name}

my age is: ${age}
`;

console.log(multilineString);

compatibility :

  • It was introduces in ES6//es2015
  • It is now natively supported by all major browser vendors (except internet explorer)

Check exact compatibility in Mozilla docs here

美人骨 2024-11-10 12:40:06

ES6 的方法是使用模板文字:

const str = `This 

is 

a

multiline text`; 

console.log(str);

更多参考 这里

The ES6 way of doing it would be by using template literals:

const str = `This 

is 

a

multiline text`; 

console.log(str);

More reference here

巡山小妖精 2024-11-10 12:40:06

您可以使用 TypeScript (JavaScript SuperSet),它支持多行字符串,并且无需开销即可转换回纯 JavaScript :

var templates = {
    myString: `this is
a multiline
string` 
}

alert(templates.myString);

如果您想使用纯 JavaScript 完成相同的任务:

var templates = 
{
 myString: function(){/*
    This is some
    awesome multi-lined
    string using a comment 
    inside a function 
    returned as a string.
    Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)

}
alert(templates.myString)

请注意,iPad/Safari 不支持 'functionName.toString()'

如果您有大量遗留代码,您还可以使用TypeScript 中的纯 JavaScript 变体(用于清理目的):

interface externTemplates
{
    myString:string;
}

declare var templates:externTemplates;

alert(templates.myString)

您可以使用纯 JavaScript 变体中的多行字符串对象,将模板放入另一个文件中(您可以将其合并到包中)。

您可以在
处尝试 TypeScript
http://www.typescriptlang.org/Playground

You can use TypeScript (JavaScript SuperSet), it supports multiline strings, and transpiles back down to pure JavaScript without overhead:

var templates = {
    myString: `this is
a multiline
string` 
}

alert(templates.myString);

If you'd want to accomplish the same with plain JavaScript:

var templates = 
{
 myString: function(){/*
    This is some
    awesome multi-lined
    string using a comment 
    inside a function 
    returned as a string.
    Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)

}
alert(templates.myString)

Note that the iPad/Safari does not support 'functionName.toString()'

If you have a lot of legacy code, you can also use the plain JavaScript variant in TypeScript (for cleanup purposes):

interface externTemplates
{
    myString:string;
}

declare var templates:externTemplates;

alert(templates.myString)

and you can use the multiline-string object from the plain JavaScript variant, where you put the templates into another file (which you can merge in the bundle).

You can try TypeScript at
http://www.typescriptlang.org/Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文