1

How can I use javascript to add a number (any number between 0-100) followed by a underscore, before the variable value?

Example:

 2000 becomes 12_2000 //a number of my choice is added followed by an underscore hello becomes 12_hello 

The number (12 in this case) is a constant chosen by me!

Thanks

0

7 Answers 7

2

i + '_' + x where i is the number and x is an arbitrary value.

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

Comments

2

Just use string concatenation:

var res = '12_' + myNum; 

Or with a variable prefix:

var res = prefix + '_' + myNum; 

Comments

0

This is just basic string concatenation, which can be done with the + operator:

var num = 2000; "12_" + num; // "12_2000" 

Comments

0
var_name = "2000"; output = "12_" + var_name; 

Comments

0
function prefixWithNumber(value, number) { return number + "_" + value; } 

This expression is evaluated as (number + "_") + value. Since one of the operants in the first addition is a string literal, the second argument number is converted (coerced) to a string. The result is a string, which causes the third argument to be converted to a string as well.

This is what the JS engine does behind the scenes:

(number.toString() + "_") + value.toString(); 

Comments

0

Maybe you're looking for something like this:

Object.prototype.addPrefix = function(pre){ return pre + '_' + this; }; 

This allows code like:

var a = 5; alert(a.addPrefix(7)); 

or even:

"a string".addPrefix(7); 

Comments

0

Joining an array can be faster in some cases and more interesting to program than "+"

[i, '_', myNum].join('') 

Comments