简体   繁体   中英

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 .

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);

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 .

Javascript doesn't have 'reverse' operator for strings, but there is Array.reverse() function which can help you in such cases:

var hello = "hello";

hello = (hello + ",world, beautiful").split(",").reverse().join(' ');

console.log(hello);  // beautiful world hello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM