Reputation: 2859
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?
Upvotes: 3
Views: 755
Reputation: 303
assign the variable to itself like
var string = "hello";
string = string.toUpperCase();
Upvotes: 0
Reputation: 30587
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.
Upvotes: 3
Reputation: 16510
Strings in JavaScript pass exist as values, not references, so you've got it: reassignment.
string = string.toUpperCase()
Upvotes: 0