您可以使用String#replace
用正則表達式
var regex = /^[.,?!'"]+|[.,?!'"]+$/g;
text = text.replace(regex, '');
正則表達式說明:
^
:開頭的行anchor
$
的:行尾anchor
[.,?!'"]+
:匹配的任何字符的是,在任何順序
|
發生一次或多次character class[
和]
:在正則表達式OR condition/alteration
g
:全局標誌
RegEx101 Live Demo
var regex = /^[.,?!'"]+|[.,?!'"]+$/g; // Note that you don't need `m` flag here
var resultEl = document.getElementById('output');
document.getElementById('myInput').addEventListener('keyup', function() {
resultEl.innerHTML = this.value.replace(regex, '');
}, false);
<input type="text" id="myInput" placeholder="Type something" />
<div id="output">You'll see output here</div>
從OP的comment
如何調整正則表達式,以便它如果變量與's
結束刪除字符?例如,如果變量是約翰的,它將成爲約翰
正則表達式可以修改了一下,在字符串的結尾匹配's
。
字符類可以變成懶/非貪心,並且在字符串結尾添加's
作爲可選組。
/^[.,?!'"]+|[.,?!'"]*?(?:'s)?$/
添加?
在[.,?!'"]*?
會使比賽lazy。 (?:)
是non-capturing group並且在(?:'s)?
中加入?
將使得's
可選。
RegEx Demo
或者,如@Daniel Cheung在comment說,你也可以使用
/^[.,?!'"]+|(?:[.,?!'"]|'s)+$/
RegEx Demo
更新:
要刪除空格\s
中可以添加cha類別。或者String#trim
也可以在`替換後使用。
/^[.,?!'"\s]+|[.,?!'"\s]+$/
^^ ^^
RegEx Demo
正如@Casimir et Hippolyte在comment所述,您可以使用^[\W_]+|[\W_]+$
來開頭刪除所有的特殊字符和結束串的。
**非常好!我有個問題。如果變量以**的**結尾,我該如何調整正則表達式以便刪除字符?例如,如果變量是** John's **,它將變成** John ** –
@HenrikPetterson'^ [。,?!'「] + |(?:[。,?!'」] |的s )+ $'' –
這太好了。我會接受這個答案,並獎勵它50分!只是最後一個問題。如果文本在結尾或開始處有空格,則不起作用。你可以調整正則表達式來忽略開始或結束處的空間嗎? –