Creating multiline strings in JavaScript

2018-12-30 23:10发布

I have the following code in Ruby. I want to convert this code into JavaScript. what's the equivalent code in JS?

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

30条回答
深知你不懂我心
2楼-- · 2018-12-30 23:18

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.

查看更多
初与友歌
3楼-- · 2018-12-30 23:18

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

查看更多
忆尘夕之涩
4楼-- · 2018-12-30 23:20

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

查看更多
永恒的永恒
5楼-- · 2018-12-30 23:22

I think this workaround should work in IE, Chrome, Firefox, Safari, Opera -

Using jQuery :

<xmp id="unique_id" style="display:none;">
  Some plain text
  Both type of quotes :  " ' " And  ' " '
  JS Code : alert("Hello World");
  HTML Code : <div class="some_class"></div>
</xmp>
<script>
   alert($('#unique_id').html());
</script>

Using Pure Javascript :

<xmp id="unique_id" style="display:none;">
  Some plain text
  Both type of quotes :  " ' " And  ' " '
  JS Code : alert("Hello World");
  HTML Code : <div class="some_class"></div>
</xmp>
<script>
   alert(document.getElementById('unique_id').innerHTML);
</script>

Cheers!!

查看更多
无色无味的生活
6楼-- · 2018-12-30 23:22

If you happen to be running in Node only, you could use the fs module to read in the multi-line string from a file:

var diagram;
var fs = require('fs');
fs.readFile( __dirname + '/diagram.txt', function (err, data) {
  if (err) {
    throw err; 
  }
  diagram = data.toString();
});
查看更多
回忆,回不去的记忆
7楼-- · 2018-12-30 23:23

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>
查看更多
登录 后发表回答