Olga Olga - 1 month ago 9
Javascript Question

Remove specific character at the end of each word using regular expression

So far I was able to remove the unwanted character only at the end of the whole string. But I have no idea how to achieve the same result at the end of each word, without removing it at the beginning of each word.

Here is what I've got.

function removeCharacter(str){
return str.replace(/[!]*$/g, '');
}

console.log(removeCharacter('Hello, my name is Ivan Ivanych.!'));
console.log(removeCharacter("!!Hello there.!!"));
console.log(removeCharacter("Hello,!!! I!! am! Ivan."));
console.log(removeCharacter("!!!Hello,!!! !!I!! !am! Ivan."));

Answer

This will do what you want:

function removeCharacter(str){
  return str.replace(/([a-z,.])!+/gi, '$1');
}

console.log(removeCharacter('Hello, my name is Ivan Ivanych.!'));
console.log(removeCharacter("!!Hello there.!!"));
console.log(removeCharacter("Hello,!!! I!! am! Ivan."));
console.log(removeCharacter("!!!Hello,!!! !!I!! !am! Ivan."));