Is there a reverse concatenation operator for Javascript strings?
Asked Answered
F

4

6

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.

Fortunna answered 18/2, 2016 at 19:14 Comment(2)
No, there's no shorthand for that.Salubrious
" world" += hello;, works but you need to capture the output.Subcontinent
C
3

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.

Cooperman answered 18/2, 2016 at 19:26 Comment(0)
F
2

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);
Forbearance answered 18/2, 2016 at 19:22 Comment(1)
In Java it's look like this: String title = title.concat("-"+title); Thank you.Hasen
N
1

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
Neodymium answered 18/2, 2016 at 19:22 Comment(0)
S
0

Concat returns the array without modifying existing arrays so where as you have

a= a.concat(b) // to put b at the end of a

You could just as easily do a = b.concat(a)? // put b followed by a. IE b at the beginning of the list a

Squab answered 6/7, 2021 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.