Putting Variables inside quotes in JavaScript
November 10, 2018 3:35 PM   Subscribe

With a piece of Javascript like this: form.vals({"prizePot":"830"}); How would I write it if I wanted to replace 830 with a variable named newPrizePot?
posted by willnot to Computers & Internet (5 answers total)
 
Best answer: form.vals({"prizePot": newPrizePot});

Unless you mean, replace it with a variable named newPrizePot and add quotes on either side, in which case

form.vals({"prizePot":'"' + newPrizePot + '"'});
posted by mustardayonnaise at 3:43 PM on November 10, 2018


Response by poster: Thanks, mustardayonnaise. I could have sworn I tried both of those variations, but the first one is working now, so there must have been some typo I was missing.
posted by willnot at 3:49 PM on November 10, 2018


Yeah, JavaScript doesn't have string interpolation, you have to use straight up + style concatenation.
posted by rhizome at 3:50 PM on November 10, 2018


Yeah, JavaScript doesn't have string interpolation, you have to use straight up + style concatenation.

It was added in ES6. So it's there in newer browsers, but anything before 2015 or 2016 will just throw a syntax error on it.
posted by firechicago at 4:16 PM on November 10, 2018 [1 favorite]


To clarify a bit here about why the solution you used is the one you wanted, you didn't ever actually want to put anything into quotes. The quotes denote that "830" is a string. You have some data in newPrizePot; if it's a string, it's already good. If it isn't a string, a lot of things in JavaScript that call for a string will just treat it like it's a string anyway.

So you didn't want to replace the number 830 inside that string with newPrizePot, you wanted to replace the string "830", with the quotes, with newPrizePot. So yeah, everything but IE can handle template literals, but at the level of stuff you're actually doing, don't worry if that doesn't make sense, because it's not what you're trying to do.
posted by Sequence at 4:20 PM on November 10, 2018


« Older Super soft men’s long sleeve collared button down...   |   Learning boring stuff for an interview Newer »
This thread is closed to new comments.