js正则 - 显示或者保存正则表达式匹配的部分内容

来源:互联网 发布:淘宝店铺导航字体代码 编辑:程序博客网 时间:2024/05/16 09:24

代码使用方法:

有如下电话号码:

13588888333
13658447322
13558885354
13587774654
13854554786

要求,要求只匹配135开头的电话,但是匹配结果只保留135后面的数字。

由于JavaScript里的正则不支持(?=xx)xxx的模式,只支持xxx(?=xx)的模式。所以只能将135后面的内容作为一个子正则表达式匹配的内容,然后再在后面引用。


<textarea class="codecontainer" id="codebox0" onfocus="this.style.posHeight=this.scrollHeight" onpropertychange="this.style.posHeight=this.scrollHeight" style="height: 242px" name="codebox0"> Carl给出的函数如下: function f(phoneNumber) { var pattern = /^(135)(/d{8})$/; if(pattern.test(phoneNumber)) return phoneNumber.replace(pattern,&quot;$2&quot;); else return &quot;不是135打头的手机号码!&quot;; } /^(135)(/d{8})$/ </textarea>


正则中,135作为开头表示第一个子正则表达式,第二个括号内的子正则表达式则匹配后面的8个数字,然后在replace中使用$2就可以引用这个子正则表达式匹配的内容了。测试代码如下:

<textarea class="codecontainer" id="runtimecodebox0" onfocus="this.style.posHeight=this.scrollHeight" onpropertychange="this.style.posHeight=this.scrollHeight" style="height: 466px" name="runtimecodebox0"> &lt;script type=&quot;text/javascript&quot;&gt; function f(phoneNumber) { var pattern = /^(135)(/d{8})$/; if(pattern.test(phoneNumber)) return phoneNumber.replace(pattern,&quot;$2&quot;); else return &quot;不是135打头的手机号码!&quot;; } var arr = new Array( &quot;13588888333&quot;, &quot;13658447322&quot;, &quot;13558885354&quot;, &quot;13587774654&quot;, &quot;13854554786&quot; ); for(var i = 0; i &lt; arr.length; i++) document.write(f(arr[i])+'&lt;br /&gt;'); &lt;/script&gt; </textarea>