Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript passing String Array to String literal

I want to pass Array of string values to a string literal as follows

Code :

var array = ['1','2556','3','4','5'];
...
...

var output = `
<scr`+`ipt>
    window.stringArray = [`+ array +`]
</scr`+`ipt>

`

Output :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script>
    window.stringArray = [1,2556,3,4,5]
</script>

Desired Output:

<script>
    window.stringArray = ['1','2556','3','4','5']
</script>

I’ve tried to not string the arrays and string it inside the multiline string, but the values are too long for int to handle and it breaks e.g. [888555985744859665555] this will turn into [888555985744859665500] and it’s a push on the memory, easy to use string regardless!
Next I’ve tried to use map function within the inline string like this

`[`+ array.map(String) +`]`

I can’t add any more lines to the output string mentioned above, code can be modified within the one line or added above it!

>Solution :

You can stringify the array. In addition just escape the / instead of using concatenation on the tag name – it’s easier to read, and more efficient.

const array = ['1','2556','3','4','5'];

const output = `
  <script>
    window.stringArray = ${JSON.stringify(array)}
  <\/script>
`;

console.log(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading