Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reverse concatenation operator for Javascript strings?

In Javascript,

hello += ' world'
// is shorthand for
hello = hello + ' world'

Is there a shorthand operator for the opposite direction?

hello = ' world' + hello

I tried hello =+ ' world' but it did not work: it just typecast ' world' into NaN and then assigned it to hello.

like image 599
chharvey Avatar asked Feb 18 '16 19:02

chharvey


2 Answers

Is there a shorthand operator for the opposite direction?

No, all JavaScript compound assignment operators take the target as the left-hand operand.

Just use the hello = ' world' + hello; statement that you had. If you're doing this repetively, consider using an array as a buffer to which you can prepend by the unshift method.

like image 105
Bergi Avatar answered Sep 28 '22 03:09

Bergi


There is not really a shorthand for what you are describing.

An alternative approach would be to use String's concat function:

var hello = 'hello';
var reverse = 'world '.concat(hello);
like image 23
Jonathan.Brink Avatar answered Sep 28 '22 02:09

Jonathan.Brink