1

I cannot understand why my word[1] returns an a instead of an i, could you help me understanding it?

var word = 'tangle';
document.write(word[1]); //returns 'a'
word[1] = 'i';
document.write(word[1]); //returns 'a'

(truth is, I wanted to make this, is my method wrong?)

//convert the first letter of each word of the string in upper case
var string = 'the quick brown fox';
stringSpl = string.split(' ');
for (var j=0; j<stringSpl.length; j++){
  stringSpl[j][0] = stringSpl[j][0].toUpperCase(); //this line is the faulty one
}
document.write(stringSpl.join(' '));
0

3 Answers 3

2

Strings are immutable in Javascript.

In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it.

Source: David Flanagan, in his book "JavaScript, The Definitive Guide, 4th edition" (ISBN: 978-0613911887).

Sign up to request clarification or add additional context in comments.

2 Comments

Cite your sources. Who wrote this text?
Edited answer with source.
1

Strings in JavaScript are immutable; rather than modifying them, you have to create a modified copy.

Note that word[1] is just syntactic sugar for word.charAt(1); just as you wouldn't expect word.charAt(1) = ... to modify the character returned by word.charAt(1) (because it's not returned by reference), you can't expect word[1] = ... to do so, either.

For your example, you can write something like this:

var string = 'the quick brown fox';
var titleCasedString =
  string.replace(/(^| )( )/g, function ($0, $1, $2) {
    return $1 + $2.toUpperCase();
  });
document.write(titleCasedString); // writes 'The Quick Brown Fox'

(using the replace method of string objects).

Comments

0

Strings are not Arrays, but you can use an indexer syntax (similar to that of Arrays) to get characters from them.

You cannot, however, set elements using the same syntax.

Use String.prototype.split to create an Array from a String.

Comments

Your Answer

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.