Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript string object readonly?

a=new String("Hello");

String("Hello")

a[0]==="H" //true
a[0]="J"
a[0]==="J" //false
a[0]==="H" //true

Does this mean I can only use Strings as arrays of char's by .split("") and then .join("")?


ANSWER: Yes, in Javascript strings are readonly (aka immutable) This question is answered here at:

  • Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
  • What does immutable mean?
like image 670
TiansHUo Avatar asked Sep 21 '12 09:09

TiansHUo


People also ask

How do you check if a property is readOnly in JavaScript?

Use the readOnly property to check if an element is read-only, e.g. if (element. readOnly) {} . The readOnly property returns true when the element is read-only, otherwise false is returned.

What does read-only mean in JavaScript?

The readOnly property sets or returns whether a text field is read-only, or not. A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it. Tip: To prevent the user from interacting with the field, use the disabled property instead.

What is a string in JavaScript?

A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. Strings in JavaScript are primitive data types and immutable, which means they are unchanging.


2 Answers

Strings are immutable, so yes. a should be reassigned if you want to change the string. You can also use slice: a = 'j'+a.slice(1), or a replace: a = a.replace(/^h/i,'j').

You could create a custom mutable String object, something like this experiment (esp. see method replaceCharAt).

like image 140
KooiInc Avatar answered Sep 30 '22 09:09

KooiInc


Thats correct.

You can of course build a function to handle this for you.

See this SO Post for different examples of this:

How do I replace a character at a particular index in JavaScript?

like image 41
Curtis Avatar answered Sep 30 '22 10:09

Curtis