10

A silly question I guess, how can we convert a String object in javascript to a String primitive ?
Problem is I am having a map in which key is a String literal and it is not giving any result if I am passing a String object to it. Any way i can covert that string object to primitive to get the results from map ?

snow_leopard
  • 1,466
  • 2
  • 20
  • 36

1 Answers1

9

You can use the valueOf method to extract the primitive value from a wrapper object:

var sObj = new String("foo");
var sPrim = sObj.valueOf();

Wrapper objects (String, Boolean, Number) in JavaScript have a [[PrimitiveValue]] internal property, which holds the primitive value represented by the wrapper object:

[[PrimitiveValue]]: Internal state information associated with this object. Of the standard built-in ECMAScript objects, only Boolean, Date, Number, and String objects implement [[PrimitiveValue]].

This primitive value is accessible via valueOf.

apsillers
  • 112,806
  • 17
  • 235
  • 239