Correct way to permanently change JavaScript string

In Ruby, if I want to change a string and change its original string, I can use the !

bang symbol .

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

      

In JavaScript, I cannot find this equivalence. Changing a string to be upperCase

, for example, returns the original string after the first instance.

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

      

I know I can store it as a variable like

var upperCaseString = string.toUpperCase();

      

but this seems ineffective and undesirable for my purposes.

I know this should be obvious, but what am I missing?

+3


source to share


3 answers


The return value toUpperCase

is a new string with a capital letter. If you want to keep this and discard the original use this:

string = string.toUpperCase();

      

BTW, when typing JS statements in the command line node.js and similar environments, it prints the result of evaluating each expression, so you see the uppercase version if you just type



string.toUpperCase();

      

As you deduced, that doesn't affect the original string.

+2


source


Strings in JavaScript pass exist as values, not references, so you have this: override.



string = string.toUpperCase()

0


source


assigns a variable to itself like

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

      

0


source







All Articles