Remove Character From String Using JavaScript

How To Remove Character From String Using JavaScript

Removing character from string is common problem that you encounter while developing software applications. In this tutorial, you’ll learn about different ways to remove character from string using JavaScript.

Remove First/Last Character From String Using Slice

Slice method extracts a part of the string and returns it as a new string. Let’s say you want to remove the first character of a string. So, you can specify the start index from which the string needs to be extracted. Since you want to remove the first character, you can extract from the second character (1st index).

function remove_first_character(element) {
  return element.slice(1)
}
console.log(remove_first_character('Good'))

Similarly, you can use slice to remove last character from string using JavaScript. Here is how the code looks :

function remove_last_character(element) {
  return element.slice(0,element.length - 1)
}
console.log(remove_last_character('Good'))

Remove Character From String Using Substr

Substr is another string manipulation method which can be used to remove character from string. It works quite similar to slice method.

function remove_first_character(element) {
  return element.substr(1,element.length)
}

function remove_last_character(element) {
  return element.substr(0,element.length - 1)
}
console.log(remove_last_character('Good'));
console.log(remove_first_character('Good'));

There is an interesting comparison between slice and substr on StackOverflow.

Remove Character From String Using Replace

Replace is another method that can be used to remove character from string. You can replace in combination with RegExp to remove character. You create a regular expression based on the string to remove from the actual string. Using the regular expression you replace the string from actual string. Here is how the code looks :

function remove_character(str_to_remove, str) {
  let reg = new RegExp(str_to_remove)
  return str.replace(reg, '')
}

console.log(remove_character('hello', 'helloworld'))

Wrapping It Up

In this tutorial, you learnt a couple of different ways to remove character from string using JavaScript. Have you used any other methods for character removal ? Do let us know in the comments below.