3

In Ruby, if I want to modify a string and have it change the original string, I can use the ! bang character.

string = "hello"
string.capitalize!
> "Hello"
string
> "Hello" 

In JavaScript, I can't find this equivalence. Modifying a string to be upperCase for instance returns the original string after the first instance.

var string = "hello";
string.toUpperCase();
> "HELLO"
string
> "hello"

I know I can save it as a variable such as

var upperCaseString = string.toUpperCase();

but this seems inefficient and is undesirable for my purposes.

I know it must be obvious, but what am I missing?

TryinHard
4,1263 gold badges31 silver badges55 bronze badges
asked Jul 2, 2015 at 5:01
1
  • It seems string is immutable in javascript like java. Commented Jul 2, 2015 at 5:04

3 Answers 3

3

The return value of the toUpperCase is a new string which is capitalized. If you want to keep that and throw away the original, use this:

string = string.toUpperCase();

BTW, when entering JS statements on the command line of node.js and similar environments, it prints the result of evaluating each expression, which is why you see the uppercase version if you just type

string.toUpperCase();

As you have deduced that has no effect on the original string.

answered Jul 2, 2015 at 5:05

1 Comment

Alright, that would explain why I had a tough time finding the equivalence. Thanks!
0

Strings in JavaScript pass exist as values, not references, so you've got it: reassignment.

string = string.toUpperCase()

answered Jul 2, 2015 at 5:04

Comments

0

assign the variable to itself like

var string = "hello";
string = string.toUpperCase();
answered Jul 2, 2015 at 5:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.