Possible Duplicate:
Why are there two kinds of JavaScript strings?
For example, we need to use new RegExp()
instead of the regex literal if we need the regex expression to be dynamically calculated.
However exactly what are the edge cases when anyone will ever need to use String/Number/Boolean objects as opposed to their primitive versions ? (because I can't seem to even think of one where it will ever be needed)
A String
is an Object
, but the primitive version exists which is created as a literal with 'Hello'
(and is by far the most common used).
People sometimes use new String()
to convert another type to a String
, for example, in a function.
function leadingZero(number, padding) {
number = new String(number);
...
}
Leading 0s are not significant in a Number
, so it must be a String
.
However, I still would have preferred to have made the Number
a String
by concatenating it with an empty String
(''
).
function leadingZero(number, padding) {
number += '';
...
}
This will implicitly call the toString()
of the Number
, returning a String
primitive.
I was reading that people say hey
typeof foo==="string"
is not fool-proof because if the string is created usingnew String
thetypeof
will give usobject
.
You can make a fool proof isString()
method like so...
var isString = function(str) {
return Object.prototype.toString.call(str) == '[object String]';
}
jsFiddle.
This works in a multi window
environment. You could also check the constructor
property, but this fails in a multi window
environment.
Also refer to Felix Kling's comments to this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With