remove a character from a string in javascript

There are several ways to remove a character from a string in JavaScript. Here are a few examples:

  1. Using the replace method:
index.tsx
let str = "hello world!";
str = str.replace("l", ""); // removes the first occurrence of "l"
console.log(str); // "heo world!"
127 chars
4 lines
  1. Using the splice method:
index.tsx
let str = "hello world!";
let arr = str.split("");
arr.splice(2, 1); // removes the character at index 2
str = arr.join("");
console.log(str); // "helo world!"
160 chars
6 lines
  1. Using the substring method:
index.tsx
let str = "hello world!";
str = str.substring(0, 2) + str.substring(3); // removes the character at index 2
console.log(str); // "heo world!"
142 chars
4 lines

Note that all of these methods create a new string with the character removed, rather than modifying the original string.

gistlibby LogSnag