How to pass a String Array to a String literal in JavaScript

I need to pass an array of string values to a string literal in the following way

Code :

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

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

`

Output :

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

Desired Output:

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

I attempted to avoid converting the arrays into strings and instead include them inside the multiline string, but the values are too large for integer handling and get truncated e.g. [888555985744859665555] becomes [888555985744859665500] causing memory issues, so it is preferable to use strings! I also tried using the map function within the inline string like this

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

I am unable to add more lines to the existing output string mentioned above, any modifications should be implemented within the one line or added above it!

Answer №1

One way to manipulate the array is by using the JSON.stringify method. Another tip is to escape special characters like '/' rather than concatenating them to improve code readability and efficiency - as pointed out here.

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

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

console.log(output);

Answer №2

Have you considered utilizing JSON.stringify? It's a great solution for your specific scenario!

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

var result = `
<scr`+`ipt>
    window.numbersArray = `+ JSON.stringify(numbers) +`;
</scr`+`ipt>

`;

console.log(result);

To learn more about the benefits of using JSON.stringify, check out this resource on MDN: here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hide all the div elements on the web page and only display one when a button is clicked

I have successfully set up a few buttons that can show and hide divs on click. However, I am wondering if it is possible to hide all other divs when one is showing, and also have "divone" show up on load. Buttons: <button class="btn btn-outline-primar ...

I am puzzled as to why my text and div boxes are displaying in my navbar/hamburger menu instead of at the bottom of the page

Greetings, everyone! This is my debut post here so bear with me if it's not presented in the correct format. Currently, I am deep into creating a website using HTML, CSS, and just a hint of JavaScript. My primary focus right now is on building the ho ...

Changing Three.js from mouse interaction to a random movement pattern

Recently, I came across this interesting website with a background that lights up depending on the movement of your mouse. I was wondering if there is a way to make that illuminated spot move around on its own. If you want to see how it looks, check out th ...

React application experiencing freezing when setInterval function is utilized

I've been working on incorporating Conway's Game of Life into a React project, but I'm encountering freezing issues whenever a new generation is triggered. My assumption is that the problem lies in the excessive overhead from constant DOM re ...

Ways to programmatically compare all elements between two separate arrays

Is there a way to create a process where the first loop iterates through the elements of one array, while another loop goes through a second array and compares each element in the first array with all elements in the second array? For example: //first loo ...

What could be causing my vm root to be defined as app.__vue__?

I am facing an issue where my root vm in Vue is being set to app.__vue__ instead of just app. For instance, when trying to access the router, I have to use app.__vue__.$router. This seems unnecessary and confusing. There's more code in the script, bu ...

What is the process for updating a placeholder text after the user makes a guess or enters

My latest project involves creating a fun guessing game where players have to identify the driver based on the teams they have driven for. The game displays the number of guesses allowed and keeps track of how many attempts the player has made so far. For ...

Generating personalized MongoDB collections for individual users - A step-by-step guide

My query is more about the procedure rather than a specific coding issue. I am working on a node application and using DHTMLX calendar. What I aim for is to have each user with their own set of events on their individual calendar. Currently, the implement ...

Can saving data within a mongoose pre-save hook initiate a continuous loop?

Currently, I am developing an API for a forum system which includes functionalities for users, forums, and posts. In my MongoDB Database, there is a 'categories' collection where each category acts as a container for a group of forums. Each categ ...

Exploring the efficiency of AngularJS when binding to deeply nested object properties

Are there any performance differences to consider when data binding in Angularjs between the following: <div>{{bar}}</div> and <div>{{foo.bar}}</div>? What about <div>{{foo.bar.baz.qux}}</div>? Our team is working o ...

Is it possible to invoke a variadic function using an array as an argument?

Imagine a scenario where I need to pass the content of an array to a function that accepts a variable number of arguments. In simpler terms, I want to supply the contents of foo as values to printf, allowing these arguments to be passed on the stack. #i ...

Tips on updating x-label formatting (to display months in words) utilizing morris.js with Angular 5

Snapshot of my Request. I'm looking to alter the xLabel (2018-01 - to - Jan) and I am utilizing morris.js. ...

Get the Label Values Based on CheckBox Status

Is there a way to retrieve the values of labels corresponding to checkboxes in HTML? I have multiple labels and checkboxes next to each other, and I want to be able to get the label values if the checkbox is checked. Can you provide guidance on how to do ...

JS: Initiating a new keypress operation

When I press the Tab key, I want it to do something different instead of its default action. Specifically, I have a text box selected and I would like it to add spaces (essentially making the textarea behave like a text editor). How can I trigger this type ...

Images within inline blocks appear to be extending beyond their containing div as though they are

When I check my website in various browsers such as Firefox, IE, Edge, and Safari, I noticed that the images in the "My Specialties" section of the left column are extending outside of the div instead of fitting within it. This problem also occurs in Chrom ...

The function .load callback was triggered on five separate occasions

I'm currently working with the code below and I have a feeling that I'm overlooking something important but just can't seem to figure it out. Basically, when the user clicks a button, a fragment of the page is loaded. Once this loading is s ...

Error in Bootstrap table implementation leading to truncation of tbody height due to data-detail-view property

I'm currently working on integrating Bootstrap-Table's detailView feature into my project. However, when I enable data-detail-view="true" for my table, the height of the table element shrinks to 0. Strangely, clicking on any column with ...

Using a string array in a JSON model - a simple guide

Just starting out with Angular and having some difficulty integrating my JSON data effectively. Inside my service, I have temporary JSON data that is structured using a model to define the different types of information within it. My objective is to creat ...

Hidden warning to React-select for being uncontrolled

I've integrated react-select into my code: import React, {Component} from 'react'; import Select, {createFilter} from 'react-select'; let _ = require('underscore') class Test extends Component { constructor(props) ...

Is there a way to navigate by scrolling, moving a centrally-positioned SVG along a path while also resizing the SVG?

After following the instructions in this post about resizing SVGs, I managed to keep the red square on the path while resizing the SVG. However, a new issue arises when scrolling down - the red square is not moving to stay positioned at the center of the w ...