2017-07-26 89 views
1

我正試圖在字末尾刪除感嘆號。正則表達式在字末尾刪除字符 - js

例如。 remove("!!!Hi !!hi!!! !hi") === "!!!Hi !!hi !hi"

我能夠刪除所有感嘆號,但無法將其定位在單詞末尾。

以下是我目前擁有的。

function remove(s){ 
    return s.replace(/([a-z]+)[!]/ig, '$1'); 
} 
+1

我想你可以使用['.replace(/ \ b!+ \ B /克, '')'](https://regex101.com/r/ugHixG/1) –

回答

1

可以剝離! S中的在使用以下正則表達式的話結束:

"!!!Hi !!hi!!! !hi" 
    .replace(/!+\s/g, ' ') // this removes it from end of words 
    .replace(/!+$/g, '') // this removes it from the end of the last word 

結果:"!!!Hi !!hi !hi"

0

您正則表達式更改爲:

/([a-z]+)!+/ig 

Then

function remove(s){ 
    return s.replace(/([a-z]+)!+/ig, '$1'); 
} 

應該工作

0

你可以使用這個表達式

console.log("!!!Hi !!hi!!! !hi!!!".replace(/([a-z]+)[!]+/ig, '$1'))

+0

這是[ @ idmean的答案](https://stackoverflow.com/a/45320428/3832970)的副本,沒有附加價值。 –

1

你不能試試這個:

\b!+ 

它匹配!後面一個字。

0

我認爲這將是更容易不使用正則表達式,但insted的使用lastIndexOf和切片

類似:

function removeQuestionmark(inputvalue) { 
    var index = inputValue.lastIndexOf("!"); 

    if(inputValue.endsWith("!")) 
    return inputvalue.slice(0,index-1); 

    return `${inputvalue.slice(0,index-1)${inputValue.slice(index+1)}} 
} 

我沒有測試的代碼。

0

那麼你應該添加一個+,讓你多一個!

function remove(s){ 

    return s.replace(/([a-z]+)([!]+)/ig, "$1"); 
} 
相關問題