String slice assignment

R

Ron Garret

Is there a way to do string slice assignment in Javascript other than
tearing the string apart and reassembling it? I want to do the
equivalent of:

s1[x:y] = s2

in Python. Is there a better way than (something like) this?

s1 = s1.slice(0,x) + s2 + s1.slice(y)

Thanks,
rg
 
L

Lasse Reichstein Nielsen

Ron Garret said:
Is there a way to do string slice assignment in Javascript other than
tearing the string apart and reassembling it?

No. Strings in Javascript are immutable, so you can't assign to a
slice of a string.
I want to do the
equivalent of:

s1[x:y] = s2

in Python. Is there a better way than (something like) this?

s1 = s1.slice(0,x) + s2 + s1.slice(y)

Not really, no.

/L
 
R

Ron Garret

Lasse Reichstein Nielsen said:
Ron Garret said:
Is there a way to do string slice assignment in Javascript other than
tearing the string apart and reassembling it?

No. Strings in Javascript are immutable, so you can't assign to a
slice of a string.
I want to do the
equivalent of:

s1[x:y] = s2

in Python. Is there a better way than (something like) this?

s1 = s1.slice(0,x) + s2 + s1.slice(y)

Not really, no.

OK, just thought I'd ask. Thanks.

rg
 
T

Thomas Allen

No. Strings in Javascript are immutable, so you can't assign to a
slice of a string.
I want to do the
equivalent of:
s1[x:y] = s2
in Python.  Is there a better way than (something like) this?
s1 = s1.slice(0,x) + s2 + s1.slice(y)
Not really, no.

OK, just thought I'd ask.  Thanks.

This got me thinking about writing a little String.prototype method,
but due to Strings' immutability, there's no way to change the value
from within the method. This is a little better though if you find
yourself doing that sort of substitution frequently.

String.prototype.rangeReplace = function(x, y, str) {
return this.slice(0, x) + str + this.slice(y);
}
newGreeting = 'Hello'.rangeReplace(1, 3, 'oh');

Thomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,102
Messages
2,570,646
Members
47,254
Latest member
GayMilline

Latest Threads

Top