String
Strings in JavaScript are sequences of Unicode (UTF-16) characters.
const greeting = "Hello 🌐"; console.log( greeting);
There isn't a separate type for representing characters in JavaScript. If you want to represent a single character, use a string consisting of a single character.
Delimiters are single or double quotes:
const greeting = "Hello 🌐";
const congrats = 'Congratulation 🎉';
You can also use template literals, using the backtick character `.
const greeting = `Hello 🌐`;
Backtick delimiters are useful for multiline strings and embedded expressions:
const name = "Ali"; const greeting = `********** Hello ${name}! **********`; console.log(greeting);
You can call methods and properties available in the String
wrapper object directly on a primitive string
value.
const name = "Ali"; console.log(name.length); console.log(name.charAt(1)); console.log(name.toUpperCase());
The statements above work because JavaScript secretly converts the primitive string
to its wrapper object type String
.
Since ECMAScript 2015, you can access string characters similar to accessing array elements (using square bracket notation):
const animal = "cat"; console.log(animal[0], animal[1], animal[2]);
But you cannot use the square bracket notation to modify the string:
const animal = "cat"; animal[0] = "b"; console.log(animal);
Resources
See String
on MDN web docs for more details.