Find and Replace or Remove Multiple Instances of a Substring in JavaScript

A quick hack with a practical example

In JavaScript, if there is nothing much complicated that you want to find/search and then replace/remove in a given string, there is a small but effective (granted, not much efficient) hack. Find out below with an example:

Say we have a markdown text as follows:

let markdown = `This is a markdown text.

# Chapter 1
This is Chapter 1 text.


## Section 1.1
This is Section 1.1 text.


### Sub Section 1.1.1
This is Sub section 1.1.1 text


## Section 1.2
This is Section 1.2 text.

## Section 1.3
This is Section 1.3 text.

___

# Chapter 2
This is Chapter 2 text.


## Section 2.1
This is Section 2.1 text.


## Section 2.2
This is Section 2.2 text.


### Sub Section 2.2.1
This is Sub section 2.2.1 text

`;

Now we want to shift heading level by 1, that is, change heading 1 to 2, 2 to 3, 3 to 4 and so on (the way pandoc does). In markdown, # represents h1 tag in HTML, ## h2, and so on. So we want to append an extra # to each existing heading for this shift to happen. Effectively, find all # instances and replace them with ## .

The one liner to perform this operation to change all the instances is to split on what we need to find and join with what we need to replace with:

const shiftedHeadings = markdown.split("# ").join("## ");

console.log(shiftedHeadings);

With the result:

This is a markdown text.

## Chapter 1
This is Chapter 1 text.


### Section 1.1
This is Section 1.1 text.


#### Sub Section 1.1.1
This is Sub section 1.1.1 text


### Section 1.2
This is Section 1.2 text.

### Section 1.3
This is Section 1.3 text.

___

## Chapter 2
This is Chapter 2 text.


### Section 2.1
This is Section 2.1 text.


### Section 2.2
This is Section 2.2 text.


#### Sub Section 2.2.1
This is Sub section 2.2.1 text

To perform the same operation in opposite direction, that is, shifting headings to one greater we need to remove one # from each instance:

const shiftedHeadingsBackwards = shiftedHeadings.split("# ").join(" ");

console.log(shiftedHeadingsBackwards);

With the result:

This is a markdown text.

# Chapter 1
This is Chapter 1 text.


## Section 1.1
This is Section 1.1 text.


### Sub Section 1.1.1
This is Sub section 1.1.1 text


## Section 1.2
This is Section 1.2 text.

## Section 1.3
This is Section 1.3 text.

___

# Chapter 2
This is Chapter 2 text.


## Section 2.1
This is Section 2.1 text.


## Section 2.2
This is Section 2.2 text.


### Sub Section 2.2.1
This is Sub section 2.2.1 text

To remove all instances of a particular substring, simply pass empty string in join: .join("").

See also

When you purchase through links on techighness.com, I may earn an affiliate commission.