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

asked Feb 3, 2010 at 9:15
0

7 Answers 7

2

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

answered Feb 3, 2010 at 9:18
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;
answered Feb 3, 2010 at 9:18

Comments

0

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

var num = 2000;
"12_" + num;
// "12_2000"
answered Feb 3, 2010 at 9:18

Comments

0
var_name = "2000";
output = "12_" + var_name;
answered Feb 3, 2010 at 9:19

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();
answered Feb 3, 2010 at 9:20

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);
answered Feb 3, 2010 at 9:21

Comments

0

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

[i, '_', myNum].join('')
answered Feb 3, 2010 at 9:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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