簡體   English   中英

使用正則表達式從字符串中刪除一組特定字符

[英]Remove a set of specific characters from a string using Regular Expression

如何使用正則表達式刪除給定字符串中所有出現的撇號(')、連字符(-)和點(。)?

例如:約翰,。 Home'Owner-New應該返回John, HomeOwnerNew

我嘗試使用name.replace("\'", "").replace("-", "").replace(".", "")並且它有效。 但我覺得應該有更好的方法使用正則表達式。 我試過很少,但沒有運氣。 有人可以指導我正確的方向嗎?

您正在尋找的正則表達式可能是/[\.'-]/g

我附上了一個片段,其中包括基於您提供的樣本的測試。

 const originalString = "John,. Home'Owner-New" const expectedString = "John, HomeOwnerNew" const myRegex = /[\.'-]/g const newString = originalString.replace(myRegex, ""); const regexWorks = newString === expectedString; if(!regexWorks) throw Error('test failed'); console.log({originalString}); console.log({newString});

暫無
暫無

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

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