How to Remove a Character From String in JavaScript

Here are four ways to remove a character from a string in JavaScript:

  1. Using string.replace()
  2. Using string.replace() with the regex
  3. Using string.slice()
  4. Using string.substr()

Method 1: Using string.replace()

The string.replace() method replaces a specific character with an empty character.

Syntax

string.replace('character_to_replace', '')

Visual representation

Method 1 - Using string.replace() functionExample

string = "AppDividend";

str_chr_removed = string.replace('A', '');

console.log('Original String: ', string);

console.log('After character removed: ', str_chr_removed);

Output

Original String: AppDividend

After character removed: ppDividend

Method 2: Using a replace() method with a regular expression

This combination(replace() method with a regular expression) removes all occurrences of the particular character.

Syntax

string.replace( /regular_expression/g, "")

Visual representation

Method 2 - Using a replace() method with a regular expressionExample

str = "AppDividend";

str_chr_removed = str.replace(/A/g, '');

console.log('Original String: ', str);

console.log('After character removed: ', str_chr_removed);

Output

Original String: AppDividend

After character removed: ppDividend

Method 3: Using slice()

The string.slice() function is used to extract the parts of a string between the given parameters. It takes the starting and ending indexes of the string and returns the string in between these indices.

Syntax

string.slice(start_index, end_index)

Visual representation of removing the first character

Method 2 - Using a replace() method with a regular expression

Visual representation of removing the last character

Method 2 - Using a replace() method with a regular expressionExample

string = 'AppDividend';
console.log('Original String: ', string);

str_chr_removed = string.slice(1);
console.log('Removing the first character', str_chr_removed);

remove_last_char = string.slice(0, string.length - 1);
console.log('Removing the last character: ', remove_last_char);

Output

Original String: AppDividend

Removing the first character ppDividend

Removing the last character: AppDividen

Method 4: Using substr()

The string.substring() function is used to extract the part of the string between the start and end indexes or to the end of a string. It can remove a character from the specific index in the string.

Syntax

string.split(separator, limit)

Visual representation

Method 4: Using substr() method

Example

string = 'AppDividend';
console.log('Original String:', string);

str_chr_removed = string.substr(1, string.length);
console.log('After removing the first character:', str_chr_removed);

Output

Original String: AppDividend

After removing the first character: ppDividend

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.