2016-11-02 114 views
0

到目前爲止,我只能在整個字符串的末尾刪除不需要的字符。但我不知道如何在每個單詞的末尾獲得相同的結果,而不必在每個單詞的開始處將其刪除。使用正則表達式刪除每個單詞末尾的特定字符

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.")); 
+1

嘗試'/!(?!\ S)/ g'或'/!(?!\ W)/ g'。 –

+0

另一個想法:'.replace(/(\ w)!+/g,「$ 1」)'。 –

+0

預期結果是什麼? – Toto

回答

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

嘗試了這一點。它只會在單詞結尾處刪除感嘆號。

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

相關問題