简体   繁体   English

确定字符串是否在JS中具有电话号码

[英]Determine if String Has Phone Number in JS

I'm currently building a chat box and wanted to do some quick client-side validation of what users are sending. 我目前正在建立一个聊天框,并希望对用户发送的内容进行一些快速的客户端验证。 I want to be able to detect if the user sent a phone number in their message (in as many formats as possible, but general US formats would be okay) and replace it with pound signs (#). 我希望能够检测用户是否在其邮件中发送了电话号码(以尽可能多的格式,但可以使用美国的通用格式),并用井号(#)代替。 I have this implemented for emails like so: 我为电子邮件这样实现了:

var message = 'Hi. This is my email: foo@bar.com. This is my number: (970)-555-7595.';
var emailExp = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/img;

// prints: Hi. This is my email: *********. This is my number: (970)-555-7595
console.log(message.replace(emailExp, '*********'));

What I want it to look like is this: 我希望它看起来像这样:

var message = 'Hi. This is my email: foo@bar.com. This is my number: (970)-555-7595.';
var emailExp = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/img;
var phoneExp = SOME_CRAZY_PHONE_REGEX;

// prints: Hi. This is my email: *********. This is my number: ##########
console.log(message.replace(emailExp, '*********').replace(phoneExp, ##########));

Any way I can accomplish this? 我有什么办法可以做到这一点? I need it to find all instances of every phone number in the string and replace them with the pound sign. 我需要它来查找字符串中每个电话号码的所有实例,并将其替换为井号。 The expression doesn't have to be too crazy, but I'd like it to match most general US formats. 该表达式不必太疯狂,但我希望它与大多数美国通用格式匹配。

I did do some looking around for patterns but most of them validate that a complete string is a phone number. 我确实在四处寻找模式,但是其中大多数验证了完整的字符串电话号码。 I'm trying to find and replace all phone numbers in a string. 我正在尝试查找并替换字符串中的所有电话号码。 Thanks 谢谢

EDIT 编辑

I'm not looking to improve my email pattern. 我不希望改善我的电子邮件模式。 Just a pattern for phone numbers that will work in this context :) 只是在这种情况下可以使用的电话号码模式:)

The solution ended up being: 解决方案最终是:

var phoneExp = /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?/img;

As per fatcat's resolution fatcat1111's solution here . 根据Fatcat的分辨率, 此处fatcat1111的解决方案 I just needed to remove the beginning ^ character and the ending $ character. 我只需要删除开始的^字符和结束的$字符。

var phoneExp = /(\(\d{3}\))?[\s-]?\d{3}[\s-]?\d{4}/img;

此正则表达式适用于带有或不带有区号,机智或不带机智的美国电话号码的位置。

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

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