开发者

Create Dynamic Rege in Runtime

Friends its possible to create javascript dynamic regex at runtime. i create this regex:

[+]?\(?800\)?[+ .]?123?[+ .]?1234

for this 800.123.1234 number. This regex can found/accept this number on page in any format like:

(800).123.1234
+(800)1231234
+(800)1231234
(800).123.1234
800.123.1234
800.123.1234

Its work fine but i need to create rejex dynamic depends on any number that i feed in input text field. here is my working code example: http://jsfiddle.net/webdesignerart/ShbMv/

means if two numbers i have on page 800.123.1234 and 855.455.4577 i add this 855.455.4577 number to input text field then regex have to create dynam开发者_StackOverflow社区ic or parse

[+]?\(?800\)?[+ .]?123?[+ .]?1234

in this regex to find this 855.455.4577.


You can create your own regular expression object anytime using the new RegExp(str) syntax.

var str = "[+]?\\(?800\\)?[+ .]?123?[+ .]?1234";
var re = new RegExp(str);
re.exec("800.123.1234");

Note, you may need double backslashes on some declarations in order to allow a single backslash to survive into the regular expression constructor.

But, if I really understood what you were doing, there is probably a single regular expression that can be created in advance that will match what you need to match. For example, you could match all the phone numbers you have in your list with this:

\+?\(?\d\d\d\)?\.?\d\d\d\.?\d\d\d\d

zero or one plus sign
zero or one left paren
3 digits
zero or one right paren
zero or one period
three digits
zero or one period
four digits

Here's a jsFiddle that tests all your test numbers against a regular expression and extracts just the numbers out of each form to make a normalize phone number form: http://jsfiddle.net/jfriend00/43mqV/. It uses this regular expression:

\+?\(?(\d\d\d)\)?\.?(\d\d\d)\.?(\d\d\d\d)

This is the same as above, but it also captures each group of numbers so we can pick out just the numbers from the matched results.


Use \d where for the digits that can be any of 0 - 9.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜