Javascript正则表达式替换HTML中的所有电话号码

时间:2015-02-17 05:19:16

标签: javascript regex

我想根据以下规则将HTML中的所有电话号码(新加坡号码)替换为可点击的链接<a href="tel:xxxx"></a>: -

3xxx xxxx - Voice Over IP services
6xxx xxxx - Fixed Line services inclusive of Fixed Line Voice Over IP services
                       (e.g. StarHub Digital Voice and SingTel mio Voice)
7zxx xxxx - Mobile phone services (Starting 2015)
8zxx xxxx - Mobile phone services
9yxx xxxx - Mobile phone services (pager services until May 2012)

x denotes 0 to 9
y denotes 0 to 8 only.
z denotes 1 to 9 only.

所以我创建了这个正则表达式: -

(\+?65)?\s?(((3|6)[0-9]{3}\s?[0-9]{4})|((7|8)[1-9][0-9]{2}\s?[0-9]{4})|((9)[0-8][0-9]{2}\s?[0-9]{4}))\b

之后,我使用以下字符串测试了正则表达式: -

98749326
6436 6618
+65 6220 0878
00D90000000ypka
http://domain.com/resources/98749326-efa0-11e3-8c7f-22000aa41488

匹配结果如下: -

98749326
6436 6618
+65 6220 0878
http://domain.com/resources/98749326-efa0-11e3-8c7f-22000aa41488

问题是,如何省略最后一个字符串? http://domain.com/resources/98749326-efa0-11e3-8c7f-22000aa41488

最后一个字符串是随机媒体网址。因此,如果我使用正则表达式,所有媒体网址也将被替换。

我尝试使用^(\+?65)?\s?(((3|6)[0-9]{3}\s?[0-9]{4})|((7|8)[1-9][0-9]{2}\s?[0-9]{4})|((9)[0-8][0-9]{2}\s?[0-9]{4}))$工作并省略了网址,但是当我在javascript中使用时,它并没有替换所有的电话号码。

以下是我的javascript: -

var SGphoneNumberConverter;

SGphoneNumberConverter = function(html) {
  var sgPhoneRegex;
  sgPhoneRegex = new RegExp("^(\\+?65)?\\s?(((3|6)[0-9]{3}\\s?[0-9]{4})|((7|8)[1-9][0-9]{2}\\s?[0-9]{4})|((9)[0-8][0-9]{2}\\s?[0-9]{4}))$", "gi");
  return html.replace(sgPhoneRegex, "<a href=\"tel:$1 $2\">$1 $2</a>");
};

if (!/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
  $("body").html(SGphoneNumberConverter($("body").html()));
}

1 个答案:

答案 0 :(得分:0)

我建议您启用多行修改器。对仅具有单行的输入使用锚定正则表达式不会产生任何问题。但如果输入包含多行,则必须启用多行修饰符m

var sgPhoneRegex = new RegExp("^(\\+?65)?\\s?(((3|6)[0-9]{3}\\s?[0-9]{4})|((7|8)[1-9][0-9]{2}\\s?[0-9]{4})|((9)[0-8][0-9]{2}\\s?[0-9]{4}))$", "gmi");

示例:

> var s = '98749326\n6436 6618\n+65 6220 0878\n00D90000000ypka\nhttp://domain.com/resources/98749326-efa0-11e3-8c7f-22000aa41488';
undefined
> var sgPhoneRegex = new RegExp("^(\\+?65)?\\s?(((3|6)[0-9]{3}\\s?[0-9]{4})|((7|8)[1-9][0-9]{2}\\s?[0-9]{4})|((9)[0-8][0-9]{2}\\s?[0-9]{4}))$", "gmi");
undefined
> console.log(s.replace(sgPhoneRegex, '<a href="tel:$1 $2">$1 $2</a>'))
<a href="tel: 98749326"> 98749326</a>
<a href="tel: 6436 6618"> 6436 6618</a>
<a href="tel:+65 6220 0878">+65 6220 0878</a>
00D90000000ypka
http://domain.com/resources/98749326-efa0-11e3-8c7f-22000aa41488