The JavaScript RegExp Object

RegExp provides a vehicle for other JavaScript methods to conduct a batch process. For instance .replace(“oldSubStr”, “newSubStr”) would only replace the first matching pattern. By using RegExp, it can be archived for all matching patterns: .replace(new RegExp(“oldSubStr”, “flag”), “newSubStr”), or simply .replace(/oldSubStr/flag, “newSubStr”). Three flags g, i, m can be used as parameter for search: Global Search, Ignore Case and Multiline Input.

There are two problems with RegExp, however.

1. The simple way of RegExp can’t deal with string reference, such as .replace(/oldSubStr/flag, “newSubStr”). oldSubStr must be a string, not the string reference.

2. If your text, as a string data type, contains following literals, it won’t work properly:

. | * ? + ( ) { } [ ] ^ $ \

It is thought when escape sign \ added it would work. Unfortunately, in reality, it usually won’t work. It is therefore suggested when those literals exist in your text, you should write your own recursive or loop function to process it. Here is an example:

; var len = textContent.length
; for (var i=0; i‹len; i++) textContent = textContent.replace('\*', pattern)

http://www.w3schools.com/jsref/jsref_obj_regexp.asp
http://www.araxis.com/merge/topic_regexpreference.html
http://www.regular-expressions.info/reference.html
http://www.evolt.org/regexp_in_javascript

No comments:

Post a Comment

Labels