JavaScript

Last Updated: 12/14/2022

String

  • Primitive types don't have properties and methods, only objects do.
  • In JavaScript you have two kinds of string one is string primitive and other is string object.
  • String object is created using String constructor function
//Primitive
const message1 = "hello";
//Object
const message2 = new String("hello");
  • When you use the dot notation with a string primitive JavaScript engine internally wraps this with a string object,

Important Properties

  • length

Important Methods

Some method returns new string

  • includes
  • startsWith
  • endsWith
  • indexOf
  • replace
  • substr
  • split
  • toUpperCase
  • toLowerCase
  • trim
  • trimLeft
  • trimRight

Escape sequences

  • Special characters can be encoded using escape sequences
const message1 = 'This is Krishna\'s  book ';
const message2 = 'first line \n second line';

String Concatenation

  • Use + to concatenate strings
const name = "ganesh";
const age = 30;
const message = "Hi, I am " + name + ", aged " + age;

Multi Line Strings (Old Format)

const multiline = "first line \n" +
"second line \n" +
"third line";

Template Literals

  • Use back ticks to create template literals
  • You can create multi-line strings
  • You can add placeholders/variables inside template literals. The placeholder can be a valid JavaScript expression

Multiline

const multiline = `first line
second line
third line
`;

Interpolation

  • Automatic replacing of expressions with real values is called string interpolation.
const name = "ganesh";
const age = 30;
const message = `Hi, I am ${name}, aged {age}`;