-3

Wondering if it's possible to simplify the following into one variable definition:

var gpaEarned = '%%PATTERN:gpa%%'; //value for gpa is passed in dynamically
var gpa = gpaEarned.replace("Less than 2.0","1.9").replace("2.0-2.4","2.0").replace("2.5-2.74","2.5").replace("2.74-2.9","2.74").replace("3.0-3.4","3.0").replace("3.5 or Higher","3.5");

I'm looking to do something like this, if it's even possible:

var gpa = '%%PATTERN:gpa%%'.replace("Less than 2.0","1.9");

where '%%PATTERN:gpa%%' is a value that is passed in dynamically and the output of that value, is a string. This code lives inside of a creative in DoubleClick for Publishers.

adam
  • 11
  • 5
  • 2
    As written, none of the `replace()` calls would do anything, so just get rid of the second line. Obviously, that's not what you meant, so consider re-asking the question with more details. – GregL Feb 24 '16 at 23:11
  • The code as written makes no sense. – Redmega Feb 24 '16 at 23:18
  • *"if it's even possible"* - It certainly *is* possible, and would work just like that. Did you actually try it? – nnnnnn Feb 25 '16 at 00:36

1 Answers1

-1

It is possible to declare multiple variables in one statement in JavaScript.

var one = 1;
var two = 2;
var three = 3;

Is the same as

var one = 1, two = 2, three = 3;

...So in your case you could declare with one statement like so:

var gpaEarned = '%%PATTERN:gpa%%', gpa = gpaEarned.replace("Less than 2.0","1.9").replace("2.0-2.4","2.0").replace("2.5-2.74","2.5").replace("2.74-2.9","2.74").replace("3.0-3.4","3.0").replace("3.5 or Higher","3.5");

You could also do this by declaring only one variable if you don't need the gpaEarned var for anything. This is also valid:

var gpa = '%%PATTERN:gpa%%'.replace("Less than 2.0","1.9").replace("2.0-2.4","2.0").replace("2.5-2.74","2.5").replace("2.74-2.9","2.74").replace("3.0-3.4","3.0").replace("3.5 or Higher","3.5");
SeanKelleyx
  • 1,155
  • 13
  • 15
  • downvoted huh? any explaination? – SeanKelleyx Feb 24 '16 at 23:20
  • not sure why. i'm giving your solution a try. – adam Feb 24 '16 at 23:23
  • I didn't down-vote, but the question asked about simplifying it to one variable, and you've still got two variables, you've just combined the two var statements. OP also asked about calling replace() directly on the string literal, which would work fine. – nnnnnn Feb 25 '16 at 00:33
  • Ahh, I either totally misread, or this happened in the edit. I added the solution where only declaring one variable for anyone coming across the thread down the line. – SeanKelleyx Feb 25 '16 at 14:37
  • thanks everyone. apologies for maybe confusing things. i'm also pretty much a novice with this (i'm self-taught in my career), owing most of what i understand to my company's developers and the internet. – adam Feb 25 '16 at 17:08