Reactive Programming using shiny

Reactive Programming helps us to build an interactive application using shiny.

In shiny, there are three fundamental components of Reactive Programming :

  1. Reactive source
  2. Reactive endpoint
  3. Reactive conductor

Reactive source

– User input that comes through browser interface typically.
– It can be connected through multiple endpoints.


# load library
library(shiny)
#create ui
ui <- fluidPage(
  textInput('name','Enter your name'),
  
)
# create server
server <- function(input,output,session){
  
}
# Run the app
shinyApp(ui,server)

Reactive endpoint

– Something that appears in the user’s browser window, such as a plot or a table of values.
– In simple words, we can say that output that typically appears in the browser window, such as a plot or a table of values.


#load library
library(shiny)
#create ui
ui <- fluidPage(
  textInput('name','Enter your name'),
  textOutput('greeting')
  
)
#create server
server <- function(input,output,session){
  output$greeting <- renderText({
    paste('Hello ',input$name)
  })
  
}
#Run the app
shinyApp(ui,server)

Reactive conductor

– Reactive component between a source and endpoint typically used to encapsulate slow computations.


# create server
server <- function(input,output,session){
  #plot putout
  output$plot_trendy_names <- ploty::renderPlotly({ babynames %>%
      filter(name == input$name) %>%
      ggplot(val_bnames, aes(x=year, y=n)) +
      geom_col()
  })
  #table output
  output$table_trendy_names <- DT::renderDT({ babynames %>%
      filter(name== input$name)
  })
}

Reactive Expression

– A Reactive expression is an R expression that uses widget input and returns a value.
– The reactive expression will update this value whenever the original widget changes.
– Reactive expressions are lazy and cached.

To create a reactive expression we use reactive function, which takes an R expression surrounded by braces (just like render function).



ui <- fluidPage(
  numericInput('nrows', 'Number of Rows', 10, 5, 30),
  tableOutput('table'), 
  plotOutput('plot')
)
# create server
server <- function(input, output, session){
 #input 1
 
  cars_1 <- reactive({
    print("Computing cars_1 ...")
    head(cars, input$nrows)
  })
#input 2
  cars_2 <- reactive({
    print("Computing cars_2 ...")
    head(cars, input$nrows*2)
  })
 #output plot
 
  output$plot <- renderPlot({
    plot(cars_1())
  })
#output table  
  output$table <- renderTable({
    cars_1()
  })
}
# Run the app
shinyApp(ui = ui, server = server)

Note: A reactive expression can call other reactive expressions.That allows us to modularize computations and ensure that they are NOT executed repeatedly.

You should also visit
Build a Hello world shiny App With R

More about shinny App (Inputs, Outputs, Layouts)

More about shinny App (Inputs, Outputs, Layouts)

In the previous post, we had Build a Hello world shiny App With R.
In this post, we will cover some points regarding shiny Package. During this journey, we will go through these points :


#Design Layout
#Shiny Inputs
#Shiny Outputs

Design Layout

For designing layout, we use sidebarLayout() function. As we know that all the functions we write inside UI parts. As we know all the functions that we use for designing we write these functions in the UI part.


ui <- fluidPage( sidebarLayout()
)

sidebarLayout()

sidebarLayout() functions contains two different panels.

  • sidebarPanel()
  • mainPanel()

So, Now our code will look like this


#sidebarPanel syntax
ui <- fluidPage(
        sidebarLayout({
             sidebarPanel(),
             mainPanel()
})
)

Some more points about sidebarLayout() function

  • sidebarPanel() : In this panel input is stored.
  • mainPanel() : In this panel outPut is stored.

#load library
library(shiny)
library(ggplot2)

# create a html ui with html function
ui <- fluidPage(
  sidebarLayout(
     sidebarPanel(
       #taking user input
       textInput("name","Enter your Name"style="border: 2px solid;")
     ),
    mainPanel(
      plotOutput('trend')
    )
  )
)
#create a server
server <- function(input, output, session) {
  output$trend <- renderPlot({
    ggplot()
  })
}
#Run App
shinyApp(ui = ui, server = server)

OutPut:

shiny Inputs

shiny provides variety of input elements.

textInput


#load library
library(shiny)
# create a html ui with html function
ui<- fluidPage(
  textInput('name','Enter your name'),
  textOutput('name')
)
#create a server
server <- function(input, output,session){
  output$name <- renderText({
    paste('Hi ', input$name)
  })
}
#Run App
shinyApp(ui,server)

OutPut:

selectInput


#load library
library(shiny)
# create a html ui with html function
ui<- fluidPage(
  selectInput('hobby','Enter your Hobby',
              choices = c("Reading","Playing","Dancing","Swimming")),
  textOutput('result')
),
#create a server
server <- function(input, output,session){
  output$result <- renderText({
    paste('You are found of ', input$hobby)
  })
}
#Run App
shinyApp(ui,server)

OutPut:

sliderInput


#load library
library(shiny)
# create a html ui with html function
ui <- fluidPage(
  sliderInput('salary','Select your salary',
              value=30000,min=10000,max=500000),
  plotOutput('salaryResult')
)
#create a server
server <- function(input,output,session){
  output$salaryResult <- renderPlot(
       hist(rnorm(input$salary))
  )
}
#Run App
shinyApp(ui, server)

OutPut:

Build a Hello world shiny App With R

Introduction to Shiny

Shiny is R Package that allows you to turn your analysis into an interactive and engaging  Web Application using R.

In this post, we will develop a Hello World shiny application. In an upcoming post, we will explore more about the shiny package and develop more applications.

Now without wasting our time, we move for developing shiny App.

For developing a shiny we have to follow these steps :

  • Install Shiny Package
  • Load Shiny Package
  • Create a HTML UI with HTML function
  • Create a Server
  • Run the app

Install Shiny Package


# install shiny package
install.packages("shiny")

Load Shiny Package


# load shiny package
library(shiny)

Create a HTML UI with HTML function


#Create a HTML UI with HTML function
ui <- fluidPage("Hello World")

Create a Server


#create shiny server
server <- function(input,output,session){
}

Run the app


#Run the app
shinyApp(ui=ui,server=server)

Hence for building Hello World app with shiny we have write following lines of code.


# install shiny package
install.packages("shiny")
# load shiny package
library(shiny)
#Create a HTML UI with HTML function
ui <- fluidPage("Hello World")
#create shiny server
server <- function(input,output,session){
}
#Run the app
shinyApp(ui=ui,server=server)

OutPut

Now we are modifying our script and make it a little bit dynamic.
For that, we will add an input textbox When you insert your name inside the textbox. Suppose I have inserted my name inside textbox then it will contact with Hello World and complete text will be Hello World Dheeraj.

So, Now the question rises how to add an input text field for entering your name then for that purpose Shiny has defined some functions.


#taking user input
ui <- fluidPage(textInput("name","Enter your Name"),
                textOutput("q"))

Then after we will concate this input name with Hello World text as shown below.


load library
library(shiny)

# create a html ui with html function
#taking user input
ui <- fluidPage(textInput("name","Enter your Name"),
                textOutput("q"))
#create a server
server <- function(input,output,session){
  output$q <- renderText({
    paste("Hello World ",input$name)
  })
}
#Run an PP
shinyApp(ui, server)

OutPut

Get Latest CSV file from Folder using Node.js

getLatestFile.js



/***
 * Read lestest file property 
 * 
 */

const fs = require('fs')
async function getLatestFile() {
    const dirPath = '/home/dheeraj/Documents/BlogPost/Downloads';
    let dirCont = fs.readdirSync(dirPath);
    let files = dirCont.filter(function (elm) { return elm.match(/.*\.(csv)/ig); });
    for (let fileP = 0; fileP < files.length; fileP++) {
        let filsStats = fs.statSync(dirPath + "/" + files[fileP]);
        if (new Date(filsStats['birthtime']).getDate() === new Date().getDate() &&
            new Date(filsStats['birthtime']).getMonth() === new Date().getMonth() &&
            new Date(filsStats['birthtime']).getFullYear() === new Date().getFullYear() &&
            new Date(filsStats['birthtime']).getHours() === new Date().getHours() //&& 
        ) {
            return {
                fileName: files[fileP],
                fileLocation: dirPath + "/" + files[fileP]
            };
        }
    }
    return {
        fileName: 'orderFailed.png',
        fileLocation: dirPath + "/" + 'orderFailed.png'
    };
}

Generate test case
getLatestFile.test.js


const {getLatestFile} = require('./getLatestFile')

async function getLatest (){
    let latest = await getLatestFile();
     console.log(latest);
}

getLatest();

OutPut:

Download Code From git Repo

Data visualization Examples in R

In this post, We will explore more examples of Data Visualization using R. For that purpose we are using mtcars as dataset
here is a list of all the features of the observations in mtcars:

  • mpg — Miles/(US) gallon
  • cyl — Number of cylinders
  • disp — Displacement (cu.in.)
  • hp — Gross horsepower
  • drat — Rear axle ratio
  • wt — Weight (lb/1000)
  • qsec — 1/4 mile time
  • vs — V/S engine.
  • am — Transmission (0 = automatic, 1 = manual)
  • gear — Number of forward gears
  • carb — Number of carburetors

Example 1: Plot graph on X and Y axis


# include ggplot2 library
library(ggplot2)

# 1 - Map mpg to x and cyl to y
ggplot(mtcars, aes(x=mpg, y=cyl)) +
  geom_point()

# 2 - Reverse: Map cyl to x and mpg to y
ggplot(mtcars, aes(x=cyl, y=mpg)) +
  geom_point()

OutPut:

Example 2: Change the color, shape, and size of the points


# include ggplot2 library
library(ggplot2)

#chnage color,shape and Size
ggplot(mtcars, aes(x=wt, y=mpg, col=cyl)) +
  geom_point(shape=1, size=4)

OutPut:

Example 3: Add alpha and fill


# include ggplot2 library
library(ggplot2)
# Expand to draw points with alpha 0.5 and fill cyl
ggplot(mtcars, aes(x = wt, y = mpg, fill = cyl)) +geom_point(alpha=0.5)

OutPut:

Exercise 4: Change Shape and color


library(ggplot2)
# Change shape and color
ggplot(mtcars, aes(x = wt, y = mpg, fill = cyl)) +geom_point(shape=24,col="yellow")

OutPut:

Exercise 5: Change shape and Size


# include ggplot2 library
library(ggplot2)
# Define a hexadecimal color
change_color <- "#4ABEFF"
# Set the fill aesthetic; color, size and shape attributes
ggplot(mtcars,aes(x=wt,y=mpg,fill=cyl))+ geom_point(size=10,shape=23,col=change_color)

OutPut:

Explore row data using R

Understanding the structure of your Data

View dimensional

Syntax:


dim()

Example:


# dimensional of mtcars
dim(mtcars)

OutPut:

Looking your DataView dimensional

head()

  • view top of the dataset

Note: By default, it fetches 6 rows but we can also vary a number of rows.
Syntax:


head()

Example:


#head of mtcars
head(mtcars)
# we can vary number of rows
head(mtcars,n=8)

OutPut:

tail()

  • view bottom of the dataset

Example:


#Syntax:tail()
#tail of mtcars
tail(mtcars)

# we can vary number of rows
tail(mtcars,n=8)

Output:
Visualizing your data

hist()

  • view histogram of a single variable

Example:


Syntax:hist()
#histogram
hist(mtcars$mpg)

OutPut:

plot()

  • view plot of two variables

Example:


Synatx: plot()
#plot
plot(mtcars$mpg,mtcars$qsec)

OutPut:

Gather

  • Gather columns into key-value pairs

Syntax:




gather (data, key, value, ...)
/**
 *
data: a data frame
key: bare name of the new key column
value: bare name of the new value column
*/

Spread

  • Opposite of Gather
  • Spread key-value pairs into columns
  • Takes key-value pairs and spread them into multiple columns

Syntax:


spread(data, key, value)
/**
 *
 data: a data frame
 key: bare name of the column containing keys
 value: bare name of the column containing values
*/

Separating columns

  • The separate() function allows you to separate one column into multiple columns.
  • In the case of separate() function, we can also specify sep as an argument for specifying separator.

Syntax:


seperate(data, column_set, c("column1", "column2"))

Uniting column

  • Opposite of separate is unite

Syntax:


unite(data, column-set, c("column1", "column2"))

Note: we can also specify separator between these two columns

Introduction to Data Visualization in R

Data Visualization is an essential component of your skillset as a Data Scientist or Data Analyst. Data Visualization is basically a form of Visual communication.

ggplot2 is a plotting package that helps us to create complex plots from data in data frame.

ggplot2 functions built step by step by adding new elements

Install ggplot2 package




# install ggplot2

install.packages(ggplot2)

Load ggplot2 package



# include ggplot2 library

library(ggplot2)

During this discussion, we are going to use mtcars package for the dataset.
Note:
The matcars dataset contains information about 32 cars from 1973 motor trends magazine. The dataset is small but contains a variety of continuous and categorical variables.

Before describing ggplot2 in more detail just have a look mtcars dataset using str() command.



#structure of matcarsbasically
str(mtcars);

OutPut:

Have a look ggplot2 example 

Example:



# include ggplot2 library
library(ggplot2)
ggplot(mtcars , aes(x=wt, y=mpg))+geom_point()

OutPut:

Some points regarding ggplot2ppp

  • VisualizationVisual elements in ggplot2 are called geoms (as in geometric objects bars, points …)
  • The appearance and location of these geoms (size, color) are controlled by aesthetic properties.basicallybasically
  • aesthetic properties are shown by aes()
  • Variable that you want to plot is represented by aes() as shown in the previous example.
Goem layer Description
geom_bar() Create a layer with bars representing different statistical properties.
geom_point() Create a layer with data points.
geom_line() Create a layer with a straight line.
geom_smooth() Create a layer with smoother.
geom_histogram() Create a layer with a histogram.
geom_blogplot() Create a layer with text in it.
geom_text() Create a layer with a text in it.
geom_error_bar() Create a layer with error bars in it.
geom_hline and geom_vline() Create a layer with a user-defined horizontal and vertical line respectively.

How to derive iris.tidy from iris?



library(tidyr)
#Convert iris to iris.tidy using tidy function
iris.tidy <- iris %>%
  gather(key, Value, -Species) %>%
  separate(key, c("Part", "Measure"), "\\.")

print(head(iris.tidy))

How to derive iris.wide from iris?


# Load the tidyr package
library(tidyr)
# Add column with unique ids (don't need to change)
iris$Flower <- 1:nrow(iris)
# Produce the iris.wide dataset
iris.wide <- iris %>%
  gather(key, value, -Species, -Flower) %>%
  separate(key, c("Part", "Measure"), "\\.") %>%
  spread(Measure, value)

OutPut:

 

Some important functions in R

There are some important functions that we are using in Day to day life. I have categories these functions in these categories for understanding.

  • Common function
  • String Function
  • Looping function

Common function

At first, I am dealing with some common functions in R that we use in day to day life during development.

abs() : Calculate absolute value.

 Example:


  
  # abs function
  
amount <- 56.50
absolute_amount <- abs(amount)
print(absolute_amount)
sum(): Calculate the sum of all the values in the data structure.

 Example:


  
  # sum function
  
myList <- c(23,45,56,67)
sumMyList <- sum(myList)
print(sumMyList)
mean() : Calculate arithmetic mean.

 Example:


  
  # mean function
  
myList <- c(23,45,56,67)
meanMyList <- mean(myList)
print(meanMyList)
round() : Round the values to 0 decimal places by default.

 Example:


    
  ############## round function #####################
    
  amount <- 50.97
  print(round(amount));
 
seq(): Generate sequences by specifying the from, to, and by arguments.

 Example:

String Function
    
     # seq() function
     # seq.int(from, to, by)
    
  sequence_data <- seq(1,10, by=3)
  print(sequence_data)
  
rep(): Replicate elements of vectors and lists.

 Example:


    
    #rep exampleString Function
    #rep(x, times)
    sequence_data <- seq(1,10, by=3)  
    repeated_data <- rep(sequence_data,3)
    print(repeated_data)

  
sort(): sort a vector in ascending order, work on numerics.

 Example:


    
    #sort function
    
  data_set <- c(5,3,11,7,8,1)
  sorted_data <- sort(data_set)Functionround
  print(sorted_data)
  
rev(): Reverse the elements in a data structure for which reversal is defined.

 Example:


    
   # reverse function 
    String Function
  data_set <- c(5,3,11,7,8,1)
  sorted_data <- sort(data_set)
  reverse_data <- rev(sorted_data)
  print(reverse_data)
  
str(): Display the structure of any R Object.

 Example:


    
  # str function 
    
  myWeeklyActivity <- data.frame(
    activity=c("mediatation","exercie","blogging","office"),
    hours=c(7,7,30,48)
  )
  print(str(myWeeklyActivity))
  
append() : Merge vectors or lists.

 Example:


    
   #append function 
    
  activity=c("mediatation","exercie","blogging","office")
  hours=c(7,7,30,48)
  append_data <- append(activity,hours)
  print(append_data)
  
is.*(): check for the class of an R Object.

 Example:


    
  #is.*() function
    
  list_data <- list(log=TRUE,
                    chStr="hello"
                    int_vec=sort(rep(seq(2,10,by=3),times=2)))
  print(is.list(list_data))
  
as.*(): Convert an R Object from one class to another.

 Example:


    
  #as.*() function
    
  list_data <- as.list(c(2,4,5))
  print(is.list(list_data))
  

String Function

Now we are discussing some string function that plays a vital role during data cleaning or data manipulation.

These are functions of stringr package.So, before using these functions at first you have to install stringr package.


    
  # import string library
    
  library(stringr)
 
str_trim () : removing white spaces from string.

 Example:


    
    ############### str_trim ####################
    
   trim_result <- str_trim(" this is my string test. ");
   print("Trim string")
   print(trim_result)
 
str_detect(): search for a string in a vector.That returns boolean value.

 Example:


    
  ############### str_detect ####################
    
  friends <- c("Alice","John","Doe")
  string_detect <- str_detect(friends,"John")
  print("String detect ...")
  print(string_detect)
 
str_replace() : replace a string in a vector.

 Example:


    
  ############## str_replace #####################
    
  str_replace(friends,"Doe","David")
  print("friends list after replacement ....");
  print(friends);
 
tolower() : make all lowercase.

 Example:


    
  ############## tolower #####################
    
  myupperCasseString <- "THIS IS MY UPPERCASE";
  print("lower case string ...");
  print(tolower(myupperCasseString));
 
toupper() : make all uppercase.

 Example:


    
  ############## toupper #####################
    
  myupperCasseString <- "My name is Dheeraj";
  print("Upper case string ...");
  print(toupper(myupperCasseString));

 

Lopping

lapply(): Loop over a list and evaluate a function on each element.

 Some important points regarding lapply :

# lapply takes three arguments:

  1. list X
  2. function (or name the function) FUN
  3. … other argumnts

# lapply always returns list, regardless of the class of input.

Example:


    
  ############## lapply example #####################
    
  x <- list(a = 1:5,rnorm(10))
  lapply(x,mean)
 

OutPut:

Anonymous function

Anonymous functions are those functions that have no name.


    
  ############## lapply example #####################
  # Extract first column of matrix 
    
  
  x <- list(a=matrix(1:4,2,2),b=matrix(1:6,3,2))
  lapply(x,function(elt)elt[,1])
 

OutPut:


Use function with lapply


    
  ############## lapply example #####################
  # multiply each element of list with factor
    
  
  multiply <- function(x,factor){
    x * factor
  }

lapply(list(1,2,3),multiply,factor=3)
 

OutPut:

sapply(): Same as lapply but try to simplify the result.

 Example:


    
  ############## sapply example #####################
  # multiply each element of list with factor
    
  multiply <- function(x,factor){
    x * factor
  }
sapply(list(1,2,3),multiply,factor=3)
 

OutPut:

apply() : Apply a function over the margin of an array.

 Example:


    
  ############## apply function #####################
    
  mat1 <- matrix(c(1:10),nrow=5,ncol = 6)
  apply(mat1,2, sum)
 

OutPut:

tapply(): Apply a function over subsets of a vector.

 Example:


    
  ############## tapply function #####################
    
  tapply(mtcars$mpg, list(mtcars$cyl, mtcars$am), mean)
 

OutPut:

mapply():Multivariate version of lapply.

 Example:

Regex with JavaScript Part 3

Match WhiteSpaces

During searching or matching a string. We come across a situation where we need to match spaces in String literals.

For matching spaces in String literals, we use \s  which is a lowercase s.

Example:



/**
* Checking for WhiteSpaces
*/

let checkForWhiteSpaces = "Remove WhiteSpaces from everywhere";
let spaceRegex=/\s/g;
console.log(checkForWhiteSpaces.match(spaceRegex));

OutPut:

Match Non-Whitespace Characters

Previously we had seen for searching white spaces using /s which lowercase s.

Here we are looking for searching Non-Whitespace and that can be done using /S , yes using upperCase s.

Example:



/**
 * Checking for WhiteSpaces
 */

 let checkForWhiteSpaces = "Remove WhiteSpaces from everywhere";
 let spaceRegex=/\s/g;
 console.log(checkForWhiteSpaces.match(spaceRegex));

OutPut:

Specify Upper and Lower Number of Matches

We can specify the lower and upper number of patterns with quantity specifiers.

Quantity specifiers are used within curly brackets ({ and }).

Example:



/**
 * specify upper and lower number of match
 */

let myString ="mmmmmmmk";
let mySecondString ="mk";
// match word "mmmmmmmk" only it has minimum 2 and maximum 4 'm'
let myRegex=/m{2,4}k/;
console.log(myRegex.test(myString));
console.log(myRegex.test(mySecondString));

OutPut:

Specify Only the Lower Number of Matches
Passed

Sometimes we need to match only a lower number of matches.

So To specify a lower number of matches keep the lower number of matches followed by comma in curly bracket ( { n, } ).

where n is a lower number.

Example:



/**
* specify lower number of match
*/

let myString ="pinnnnnnnnnnk";
let mySecondString ="pinnk";
// match word "pinnk" only it has four or more letter of n
let myRegex=/pin{4,}k/;
console.log(myRegex.test(myString));
console.log(myRegex.test((mySecondString)));

OutPut:

Specify Exact Number of Matches

Sometimes we need to specify an exact number of matches.

To specify an exact number of pattern just add that number in curly bracket.

Example:


/**
* specify exact match
*
*/

let myString = "apple";
let mySecondString ="aple";
//p should be appear two times
let myRegex = /ap{2}l/;
console.log(myRegex.test(myString));
console.log(myRegex.test(mySecondString));

OutPut:

Check for All or None

Sometimes we are not sure about the pattern that we are searching for. 

In that case, we use ‘?’ i.e question mark which check for zero or one of the preceding element.

In other words, we can also say that the previous character is optional i.e if that exists then fine and if not then also no problem.

Example:



/**
*
* Check for All or None
*/


let american ="favorite";
let british ="favourite";
let regexPattern = /favou?rite/;

//In this example 'u' is optional
console.log(regexPattern.test(american));
console.log(regexPattern.test(british));

OutPut:

Positive and Negative Lookahead

Lookaheads are patterns in Javascript that tells to Javascript to look-ahead in your string to check for pattern further long.

It can be helpful during searching multiple patterns on the same string.

There are two kinds of Lookaheads :

  • Positive lookahead
  • Negative lookahead

Positive lookahead :

– Look to make sure the element in the search pattern is there, but won’t actually match it.

– Positive Lookahead is used as (?= …)

– Where  the ... is the required part that is not matched.

Negative lookahead :

– Look to make sure the element in the search pattern is not there.

– Negative lookahead is used as (?!...) 

– where the ... is the pattern that you do not want to be there.

Example:



/**
 * lookahead 
 * 
 */

 let myPassword = "ohMyGod123";
 let mySecondPassword ="ohmyGod";
 // regex for a string greater than 5 character long and don't begin with number and have two consequitive numbers
 let myRegex = /^(?=\w{6}(?=\D+\d{2}))/;
 console.log(myRegex.test(myPassword));
 console.log(myRegex.test(mySecondPassword));

OutPut:

Check For Mixed Grouping of Characters Passed

Sometimes we need to match a group of Characters using regular expression.
We can achieve that using () i.e parenthesis.

Example :



/**
*  Mixed grouping Characters
*/

let myString = "laptop";
// check for multiple group of characters
let myRegex = /(lap|Desk)top/;
console.log(myRegex.test(myString));

OutPut:

Reuse Patterns Using Capture Groups

Some patterns are multiple times in a string. Then it is wastage of time to write the pattern multiple times for searching in a string.

Example:



/**
* Reuse patterns using capture Groups
*
*/

let myString ="mummy mummy mummy";
let myRegex = /(\w+)\s\1/;

console.log(myRegex.test(myString));

console.log(myString.match(myRegex));

OutPut:

Use Capture Groups to Search and Replace

We can search and after that replace in string using .replace().

.replace() contains two parameters :

  • First parameter the string that we are searching for
  • Second parameter the string from which we want to replace.

Example:



/**
* Capture group for search andd replace
*/

let myString= "Baba Black Sheep";
// replace Baba Black sheep with Sheep Black Baba
let myRegex = /(\w+)\s(\w+)\s(\w+)/
let myReplacementString= '$3 $2 $1';
console.log(myString.replace(myRegex,myReplacementString));

OutPut:

Remove Whitespace from Start and End

Sometimes we come across the problem that some string contains unwanted whitespaces and that we need to remove these whitespaces from our string.
For removing start and end whitespaces from a string from we use .trim()
method.

Example:



/***
* removing whitespace from string using .trim()
*/

let hello = "   Hello, World!  ";

let result = hello.trim();
console.log(result);

OutPut: