How can I assign a multiline string literal to a variable in JavaScript, similar to Ruby’s multiline strings?

Hello Peeps!! :grin:

Well to be honest I have been a passionate developer of Ruby but JavaScript is not my cup of tea as of yet and hence I need support from this helpful community.

Here’s the syntax I use in Ruby:

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

Well the issue is: How do I write a multiline string JavaScript equivalent to this?

Help me if you know. Thanks in advance!!

Hello @MattD_Burch! Your question about creating multiline strings in JavaScript is a fantastic one, especially when you’re looking for clean and modern syntax!

The most modern and straightforward way in JavaScript is truly to use ES6 template literals with backticks:

const text = `This
Is
A
Multiline
String`;

This elegant approach preserves line breaks and spacing exactly as written within the string, just like Ruby’s heredoc syntax. It makes your code much more readable when dealing with multiline content.

I hope this helps.

Hello @MattD_Burch

If you specifically need compatibility with older environments, you can still use simple string concatenation with \n for line breaks:

const text = "This\n" +
             "Is\n" +
             "A\n" +
             "Multiline\n" +
             "String";

It’s certainly a bit more verbose than modern template literals, but this method reliably works everywhere, ensuring maximum compatibility across various JavaScript runtimes.

And yeah @joe-elmoufak’s ES6 template literals method is also worth a try.

That’s it hope you like it!

Hello @MattD_Burch

Another neat trick for creating multiline strings is to define an array of lines and then simply join them with \n:

const text = [
  "This",
  "Is",
  "A",
  "Multiline",
  "String"
].join('\n');

This approach makes multiline strings much easier to manage, especially when you are dynamically modifying lines or building complex string outputs from various data sources. It keeps your content organized and highly adaptable.

Thanks for reading! Thank you!

Heyya everyone

If you prefer, you can create a parent object with named keys for each issue, rather than relying on numeric indices:

var Issues = {
  issue1: { "ID": "1", "Name": "Missing Documentation", "Notes": "Issue1 Notes" },
  issue2: { "ID": "2", "Name": "Software Bug", "Notes": "Issue2 Notes" }
};

console.log(Issues.issue1.Name); // "Missing Documentation"

This method makes access explicit by the key name (e.g., issue1, issue2), which can be very clear for a predefined set of issues. However, it is inherently less dynamic for scenarios where you might have many issues or issues that are added programmatically, as it lacks built-in methods like push().

Hope you find this useful!! :raised_hands: