2

i have an array of strings like below

const array = ["string1", "string2", "string3"];
const total = 10000;

and i have a url that has string interpolation like below

const url = `http://localhost:8080/total=${total}&array=${array}`

which gives me back the below

http://localhost:8080/total=10000&array=[string1, string2, string3]

How can i make the array of strings to work with the string interpolation with JS.

expected result should be something like

http://localhost:8080/total=10000&array=["string1", "string2", "string3"]

Any help is appreciated

4
  • 1
    Why do you want ["string1", "string2", "string3"] in your URL? This is a very uncommon kind of value to have in a URL. Commented Dec 5, 2019 at 20:59
  • Yeah, typically when you're sending JSON objects/data to a server you're going to POST it. If you're insistent on using GET, you'd use URL parameters (like separate parameters for each string), where they can then be parsed server-side back into an array. Commented Dec 5, 2019 at 21:00
  • 1
    That is how the backend url is constructed and we don't have control on that Commented Dec 5, 2019 at 21:01
  • 3
    Yuck. In that case, JSON.stringify is the way to go, as Ori Drori said. Commented Dec 5, 2019 at 21:01

1 Answer 1

4

Convert the array to a string using JSON.stringify():

const array = ["string1", "string2", "string3"];
const total = 10000;

const url = `http://localhost:8080/total=${total}&array=${JSON.stringify(array)}`

console.log(url)

As noted by @avejidah you might need to use encodeURIComponent() to escape strings with reserved characters. Non reserved characters are A-Z a-z 0-9 - _ . ! ~ * ' ( ):

const array = ["string1", "string2", "string3"];
const total = 10000;

const url = `http://localhost:8080/total=${total}&array=${encodeURIComponent(JSON.stringify(array))}`

console.log(url)

Sign up to request clarification or add additional context in comments.

1 Comment

You probably want to encodeURIComponent, too, because the strings might have reserved characters (dots/slashes/plus/etc.).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.