1

i want to concatenate two string in javascript i.e.

$('#bio').css('font-color', result.titlecolor);

but i want to put the character # before the result.titlecolor i.e.

 $('#bio').css('font-color','#' result.titlecolor);

is this right or wrong? thanks

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
getaway
  • 8,792
  • 22
  • 64
  • 94

5 Answers5

7
$('#bio').css('color','#' + result.titlecolor);

(Edited to reflect @BoltClock's comment about 'color' versus 'font-color'.)

Brian Clapper
  • 25,705
  • 7
  • 65
  • 65
5

This:

'#' result.titlecolor

needs to be:

'#'+ result.titlecolor

In javascript the + operator concatenates to strings together (but remember strings are immutable, so you are creating a new string when you use it). It will also allow you to contatenate a string and a non-string together into a string, such as a number and a string. So this "The answer is : " + 42 becomes "The answer is : 42" The tricky part comes in because if you try and concatenate to numbers together such as 14 + 08, you don't get "1408" it adds the two numbers together to become 22. Logically this makes sense on a simple example, but it can become troublesome when are concatenating variables together which are loosely typed.

Community
  • 1
  • 1
kemiller2002
  • 113,795
  • 27
  • 197
  • 251
1
$('#bio').css('font-color', '#' + result.titlecolor);
adarshr
  • 61,315
  • 23
  • 138
  • 167
1
   $('#bio').css('font-color','#' + result.titlecolor);
Luis
  • 5,979
  • 2
  • 31
  • 51
1

The + operator serves as both the addition operator and string concatenation operator in JavaScript. So:

1 + 1                   // is 2

'The answer is: ' + 42  // is 'The answer is: 42'

'1' + '1'               // is '11' (!!!)

'1' + 1
1 + '1'                 // are also '11' (!!!!!)

As for your code, the CSS specification defines color but not font-color, so this is what you want:

$('#bio').css('color', '#' + result.titlecolor);

As a side note, if you ever run into the '1' + '1' or 1 + '1' problem (e.g. you are taking a numeric value from a text box), you have to convert the operands to numbers using the unary plus operator or the parseFloat function:

+'1' + +'1'            // is 2
PleaseStand
  • 31,641
  • 6
  • 68
  • 95