簡體   English   中英

Javascript刪除字符串中不是數字,字母和空格的所有字符

[英]Javascript remove all characters from string which are not numbers, letters and whitespace

使用JavaScript我想刪除字符串中不是數字,字母和空格的所有字符。 所以刪除'%#$&@*等字符,如下所示:

玩家必須玩! #justsaying

會成為:

玩家必須玩得很開心

我怎么能這樣做,我不確定正則表達式。

正如@ chris85所說,你可以使用正則表達式[^0-9a-zAZ]來替換所有不是字母,數字或空格的字符。

這是一個可以做你想要的功能:

function clean(str) {
    return str.replace(/[^0-9a-z-A-Z ]/g, "").replace(/ +/, " ")
}

需要第二次替換調用來刪除通過刪除空格之間的字符而產生的額外空格的運行。

使用replace

string.replace(/[^A-Z\d\s]/gi, '')

注意正則表達式末尾的兩個標志

g - 代表全局,意味着將找到正則表達式的每個這樣的實例

i - 代表不區分大小寫。 這意味着它將匹配小寫和大寫字符

使用您的字符串,它返回此輸出

"Players got to  play justsaying"

要將兩個或多個空白字符轉換為單個空格,您可以使用另一種replace現有方法。

string.replace(/[^A-Z\d\s]/gi, '').replace(/\s+/g, ' ')

這里的關鍵是+字符,它找到一個或多個。

可能更有效率地做到這一點,但我是Regex的業余愛好者。

原文

Player's got to * play! #justsaying

REGEXP

([^a-zA-Z0-9\s])

結果

Players got to  play justsaying

測試它

 const regex = /([^a-zA-Z0-9\\s])/gm; const str = `Player's got to * play! #justsaying`; const subst = ``; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log(result); 

請參閱: https //regex101.com/r/BYSDwz/4

我還為正則表達式添加了符號'因為你有單詞Player's ,所以這里是我的代碼:

var str = "Player's got to * play! #justsaying";
var result = str.replace(/[^a-z\d\s']/gi, '');

試試吧

var text = "Player's got to * play! #justsaying";
var result = text.replace(/[^A-Z\d\s]/gi,'');
console.log(result);

閱讀更多內容: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

這就是你如何匹配你有興趣刪除的角色......

[^\d\w\s]

注意:您應該使用全局修飾符

在這里測試: https//regex101.com/r/yilfcn/1請參閱這篇文章關於如何應用它: javascript regexp刪除所有特殊字符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM