Javascript not replacing single character [duplicate] - javascript

This question already has answers here:
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
(10 answers)
Closed 2 years ago.
This code does not work
var x ='hello';
x[2] ='a';
Why doesn't it work?
I am not using the replace() function

In javascript the strings are immutable, you cannot change the string using index.
The string manipulation methods such as trim, slice return new strings.

It doesn't work because of legacy behavior of promoting string values to String object wrappers with the value of the primitive string value.
So for example
"xyz".charAt(0)
is at least notionally evaluated as
(new String("xyz")).charAt(0)
because charAt is a prototype method of String objects and can be applied to a primitive string value in this manner.
The down side is that the promoted String object is never stored anywhere and, even if modified in JavaScript is immediately discarded. This is what is happening in the code posted:
var x ='hello';
x[2] ='a';
is treated as
new String(x)[2] = 'a'
followed by discarding the String object which, incidentally, has a property named 2 with value 'a'.
The general solution to this is to run JavaScript in strict mode, so that any attempt to assign a property to a primitive value which has been promoted to an object wrapper generates an error:
"use strict"
var x ='hello';
x[2] ='a';

Related

Cannot call toString() on numeric constant in Javascript [duplicate]

This question already has answers here:
Calling member function of number literal
(3 answers)
Closed 6 years ago.
toString() doesn't work on numeric literal like 5.toString(), but it works on string literal ("str".toString()) or after the numeric literal is assigned to var, like var a = 5;a.toString(). Wondering why it doesn't work for the first case?
You can do this if you wrap it in parenthesis.
(5).toString();
The first dot is the decimal mark. You need a second one to access the property:
5..toString();

What happens when we declare Array(4) in JavaScript? [duplicate]

This question already has answers here:
Javascript new Array and join() method
(5 answers)
Closed 6 years ago.
console.log(Array(4).join("hi"));
>> "hihihi"
I don't get what exactly is happening here?
join() is the opposite of split(). whereas split separates an array by the delimiting character you pass it, join will instead combine all the elements delimiting each one with whatever parameter you pass.
In this case the array is simply Array(4), so 4 undefined elements. combining these will yield "undefinedhiundefinedhiundefinedhiundefined".
Since js doesn't actually treat undefined as anything in this case, it turns it into an empty string and all you get is hihihi
edit: reference for my last statement from the join() documentation:
The string conversions of all array elements are joined into one string. If an element is undefined or null, it is converted to the empty string.

In Javascript is an String literal an object? [duplicate]

This question already has answers here:
What is the difference between string primitives and String objects in JavaScript?
(12 answers)
Closed 7 years ago.
I'm reading about the difference between String literal and String objects. See
What is the difference between string literals and String objects in JavaScript?
But I'm a bit confuse because there it's explained that you can use methods of the String Objects but technically is a String literal an String Object? I'm not asking if we can use the same methods, only if a String literal is an object. Thanks!
The term "string literal" refers to a syntactic convention for representing string values directly in code.
The code
"Hello Everyone"
is a string literal for a string with 14 characters.
The value represented by a string literal is a string primitive. It is not an object. That's why if you use:
typeof "Hello Everyone"
this will return the value "string", not "object".
JavaScript allows boxing of any string primitive to promote them to string objects under certain circumstances. Attempting to call a method on a string value is one of these circumstances. So if you call:
"Hello Everyone".toUpperCase()
the value represented by this literal will be boxed into a string Object, and the method will be called on that object.
You can check the type of a Javascript variable with the typeof operator. typeof "Hello World" and typeof String("Hello World") both return the type "string".
Also, a strict-equal check "Hello" === String("Hello") returns true, which means that they are not just value-equal but type-equal.
However, typeof new String("Hello World") returns "object".

Why can I not use toString() on a Number unless I declare it as a variable first? [duplicate]

This question already has answers here:
What is this javascript syntax?
(2 answers)
Closed 7 years ago.
For example:
var num = 5;
num.toString(2); // Returns the binary representation 101
But if I do
5.toString(2); // Error
I thought that the second example should work because it seems fine with strings. For example:
// BOTH WORK
var str = 'hi';
str.toUpperCase(); // Returns 'HI';
'hi'.toUpperCase(); // Returns 'HI';
You're running into a low-level syntactic problem. The token syntax for numbers includes the possibility of fractional parts following a decimal point. That syntax takes precedence over the overloaded meaning of . as a property reference operator. When the parser sees 5. it expects to see a fractional part of the number. Non-digits are considered an error.
If you want to use the . as a property reference, you have to satisfy the token grammar and encase the number in some construct that will allow the parser to see . the way you want:
var str = (5).toString();
There, your numeric constant is wrapped in parentheses. The . following the parentheses can be nothing other than a property reference operator, so the call to .toString() works as intended.

Difference between str[0] and str.charAt(0) [duplicate]

This question already has answers here:
string.charAt(x) or string[x]?
(7 answers)
Closed 8 years ago.
What is the difference between str[0] and str.charAt(0)? I always access specific character by simply typing str[i], where i is the index of the character I want to access (counted from 0), but last week I had good overview of open source JS code, and in every single project I saw, people use charAt method.
Is there any difference between those two ways?
[] is a more primitive way of accessing all kind of arrays.
charAt() is specific to strings.
You can access the index of any array by using [], but you can only use charAt() on a string.
But when it comes to string alone, both are one and the same.
But you should use charAt() because, it is well supported in all the major browsers, while the bracket notation will return undefined in IE7
Also, the bracket notation is simply accessed, while charAt() does some validation and doesn't return undefined, but will return an empty string ""
This
""[-4] // undefined
"".charAt(-4) // ""
You could ensure that the result would be a string.

Categories