-
Notifications
You must be signed in to change notification settings - Fork 9
Strings
davidbarna edited this page Apr 27, 2018
·
2 revisions
String
instances hold a primitive string accessible thanks to theString.prototype.valueOf()
function.
typeof '5' // "string"
typeof new String('5') // "object"
typeof new String('5').valueOf() // "string"
When an object is compared to a string,
String.prototype.valueOf()
is called internally to make the comparison.
const a = new String('foo')
const b = new String('foo')
a == b // false as a and b are type Object and reference different objects
a == 'foo' // true as the Object (a) is converted to String 'foo' before comparison
Template literals are string literals allowing embedded expressions.
You can use multi-line strings and string interpolation features with them.
Template literals are enclosed by the backtick ``
, not
'`or`"`
Template literals are a different syntax, not a different primitive of object.
;`\`` === '`' // true
;`\`` === '`' // true
;`'` === "'" // true
;`"` === '"' // true
Any new line characters inserted in the source are part of the template literal.
Regular string:
//prettier-ignore
const str = 'string text line 1\n' +
'string text line 2\n' +
'string text line 3'
//prettier-ignore
const str = "string text line 1\n" +
"string text line 2\n" +
"string text line 3"
Template string:
const str = `string text line 1
string text line 2
string text line 3`
The result string is exactly the same.
const text1 = 'string text line 1\n' + 'string text line 2'
const text2 = `string text line 1
string text line 2`
text1 === text2 // true
In order to embed expressions within normal strings, you must enclosed them inside a
${}
const a = 5
const b = 10
const text1 = 'Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.'
const text2 = `Fifteen is ${a + b} and\nnot ${2 * a + b}.`
text1 === text2 // true
console.log(text1)
// "Fifteen is 15 and
// not 20."