使用javascript获取字符串中的电话号码 [英] Grab a phone number inside a string with javascript

查看:62
本文介绍了使用javascript获取字符串中的电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在谷歌搜索并浏览了所有的 stackoverflow,但没有一个正则表达式有效.

I've been googling and going through all of stackoverflow and not one regex worked.

我只是想从这样的字符串中获取电话号码:

I'm simply trying to grab the phone number from strings like this:

电话:123-456-7890

Lorem ipsum dolor sat amet,consectetur adipiscing 精英.Nullam lobortis ullamcorper neque ut euismod.Curabitur convallis 1-800-123-4567 luctus posuere.Suspendisse placerat porta urna, vel bibendum odio aliquet ut.在 posuere Tortor 中的古怪.Vivamus sodales risus non dapibus posuere.sed odio est.

我在网上找到的用于电话验证的每个正则表达式字符串都不起作用.我假设是因为验证只需要字符串中的数字,而不是文本和空格.

Every regex string that I found online for phone validation doesn't work. I assume because the validation only expects the a number in the string, not text and white spaces.

推荐答案

这是一个正则表达式示例,可以找到与示例中的电话号码类似的电话号码.它可能不适用于评论中提到的某些示例,但它可能是您正在寻找的.这个函数直接来自这个相关的SO帖子.运行下面的代码片段以查看行为.

Here is a regex example that can find a phone number like the one in your example. It might not work on some of the examples like were mentioned in the comments, but it may be what you are looking for. This function is taken directly from this related SO post. Run the snippet below to see the behavior.

var regex = new RegExp(
                "\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]\\d{2,})+",
                "g"
            );

var possiblePhoneNumbers = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam lobortis ullamcorper neque ut euismod. Curabitur convallis 1-800-123-4567 luctus posuere. Suspendisse placerat porta urna, vel bibendum odio aliquet ut. Quisque in posuere tortor. Vivamus sodales risus non dapibus posuere. Sed odio est.", "Find another one right here 1-888-999-1010 or can it?"];

for (var i=0; i < possiblePhoneNumbers.length; i++) {
    document.write('<br />');
    document.write(possiblePhoneNumbers[i] + ' => ');
    document.write('<br />');
    while (match = regex.exec(possiblePhoneNumbers[i])) {
        document.write("Phone # in string: " + match[0]);
    }
    document.write('<br />');
}

这篇关于使用javascript获取字符串中的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆