Lets Start with JS: Strings
JavaScript is a powerful programming language that can add interactivity to a website.
JavaScript has 8 Datatypes
1.String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object
Lets start with some key points of String
Defining String
Strings can be created as primitives, from string literals, or as objects, using the String()
constructor:
const string1 = "A string primitive";
const string2 = 'Also a string primitive';
const string3 = `Yet another string primitive`;
const string4 = new String("A String object");
Character Access
There are two ways to access an individual character in a string. The first is the charAt()
method. he other way is to treat the string as an array-like object
"cat".charAt(1); // gives value "a"
"cat"[1]; // gives value "a"
String primitives and String objects
JavaScript distinguishes between String
objects and primitive string values.String
objects are treated as all other objects are, by returning the object.
const strPrim = "foo"; // A literal is a string primitive
const strPrim2 = String(1); // Coerced into the string primitive "1"
const strPrim3 = String(true); // Coerced into the string primitive "true"
const strObj = new String(strPrim); // String with new returns a string wrapper object.
console.log(typeof strPrim); // "string"
console.log(typeof strPrim2); // "string"
console.log(typeof strPrim3); // "string"
console.log(typeof strObj); // "object"
Common Instance/prototype methodsString.prototype.at(), includes(),
indexOf(),.replace(),.replaceAll(),slice(),split(),substring(),toLowerCase(),.toString(),trim()
String Immutability
Javascript String is immutable, which means once a String object is assigned to String reference the object value cannot be changed. However, we can still assign a new object to a String reference.
var myVar = "Hello World";
myVar.toUpperCase();
console.log(myVar) //"Hello World"
Here myVar is still “Hello World” and not HELLO WORLD. The method will return a new String object it will not change the existing String reference. So we have to assign it to a new variable to get the desired value.
We also cannot assign a new character to an index in String by square bracket notation. As Strings are immutable, by doing that we will be updating the content of String reference which cannot be possible in case of immutability.
var myVar = "Hello";
myVar[0] = "i";
console.log(myVar) //Hello
These were some important and basic points of our first data type i.e String
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
https://medium.com/@codesprintpro/javascript-string-immutability-ead81df30693