Home > front end >  JavaScript remove a character from a string and remove the previous character
JavaScript remove a character from a string and remove the previous character

Time:09-13

How do I remove a character from a string and remove the previous character as well?

Example:

"ABCXDEXFGHXIJK"

I want to split the string by "X" and remove the previous character which returns

"ABDFGIJK" // CX, EX, HX are removed

I found this thread but it removes everything before rather than a specific amount of characters: How to remove part of a string before a ":" in javascript?

I can run a for loop but I was wondering if there was a better/simpler way to achieve this

const remove = function(str){
  for(let i = 0; i < str.length; i  ){
    if(str[i] === "X") str = str.slice(0, i - 1)   str.slice(i   1);
  }
  return str
}

console.log(remove("ABCXDEXFGHXIJK")) // ABDFGIJK

CodePudding user response:

You can use String.prototype.replace and regex.

"ABCXDEXFGHXIJK".replace(/.X/g, '')

The g at the end is to replace every occurrence of .X. You can use replaceAll as well, but it has less support.

"ABCXDEXFGHXIJK".replaceAll(/.X/g, '')

If you want it to be case insensitive, use the i flag as well.

"ABCXDEXFGHXIJK".replace(/.x/gi, '')

CodePudding user response:

The simplest way is to use a regular expression inside replace.

"ABCXDEXFGHXIJK".replace(/.X/g, "")

.X means "match the combination of X and any single character before it, g flag after the expression body repeats the process globally (instead of doing it once).

CodePudding user response:

While not the most computationally efficient, you could use the following one-liner that may meet your definition of "a better/simpler way to achieve this":

const remove = str => str.split("X").map((ele, idx) => idx !== str.split("X").length - 1 ? ele.slice(0, ele.length - 1) : ele).join("");
  

console.log(remove("ABCXDEXFGHXIJK"));

CodePudding user response:

Maybe you can use recursion.

function removeChar(str, char){
     
     const index = str.indexOf(char);
     if(index < 0) return str;
     // removes 2 characters from string
     return removeChar(str.split('').splice(index - 2, index).join());
}
  • Related