到目前为止,我只能在整个字符串的末尾删除不需要的字符。但我不知道如何在每个单词的结尾处获得相同的结果,而不是在每个单词的开头删除它。
Here就是我所拥有的。
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."));
答案 0 :(得分:2)
这将做你想要的:
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."));

答案 1 :(得分:1)
试一试。它只会删除一个单词末尾的感叹号。
function removeCharacter(str){
return str.replace(/(!+)(?=\s|$)/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."));