简体   繁体   English

如何使用正则表达式从电话号码中删除空格和括号?

[英]How to remove spaces & brackets from a phone number with Regex?

How can I remove spaces and brackets from a phone number according to the following example with Regular Expressions?如何根据以下使用正则表达式的示例从电话号码中删除空格和括号?

Input: +7(999) 999 99 99 Output: +79999999999输入: +7(999) 999 99 99 Output: +79999999999

I tried the following code, but it didn't work for me:我尝试了以下代码,但它对我不起作用:

const phone = "+7(999) 999 99 99";
phone.replace(/\s/g, "");

As other people said in the comments, your provided regular expression will remove the spaces for you but if you want to remove parentheses as well you need another regex for that .正如其他人在评论中所说,您提供的正则表达式将为您删除空格,如果您还想删除括号,则需要另一个正则表达式 Keep in mind replace() method will return a new string so in order to get the new value and use it you should assign it to a new variable.请记住, replace()方法将返回一个新字符串,因此为了获取新值并使用它,您应该将其分配给一个新变量。

So your code should something like this:所以你的代码应该是这样的:

 const phone = '+7(999) 999 99 99' let newPhone = phone.replace(/\s/g, '').replace(/[()]/g, '') console.log(newPhone) // or simply do this with one replace: newPhone = phone.replace(/[()\s]/g, '') console.log(newPhone)

 const phone = '+7(999) 999 99 99'; console.log(phone.replace(/\(|\)/g, "").replace(/\s/g, ''));

I think this will help you!我想这会对你有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM