繁体   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