Jay
Jay

Reputation: 11

JavaScript remove a character from a string and remove the previous character

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

Upvotes: 0

Views: 64

Answers (5)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27202

Try this way (Descriptive comments are added in the below code snippet itself) :

// Input string
const str = "ABCXDEXFGHXIJK";

// split the input string based on 'X' and then remove the last item from each element by using String.slice() method.
const splittedStrArr = str.split('X').map(item => item = item.slice(0, -1));

// Output by joining the modified array elements.
console.log(splittedStr.join(''))

By using RegEx :

// Input string
const str = "ABCXDEXFGHXIJK";

// Replace the input string by matching the 'X' and one character before that with an empty string.
const modifiedStr = str.replace(/.X/g, "")

// Output
console.log(modifiedStr)

Upvotes: 0

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());
}

Upvotes: 0

esqew
esqew

Reputation: 44693

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"));

Upvotes: 0

nullptr
nullptr

Reputation: 4484

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, '')

Upvotes: 1

F&#39;1
F&#39;1

Reputation: 354

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).

Upvotes: 0

Related Questions