1.定義
Javascript中,定義正則表達式的方法有兩個:
1) RegExp Literal
/* /pattern/flags; */
var re = /mac/i;
2) RegExp Object Constructor
/* new RegExp("pattern","flags"); */
var re = new RegExp(window.prompt("Please input a regex.","yes|yeah"),"g");
2. Flag
1) Global Search
g The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern.
2) Flags
i The ignore case flag makes a regular expression case insensitive. For international coders, note that this might not work on extended characters such as ?, ü, ?, ?.
3) Multiline Input
m This flag makes the beginning of input (^) and end of input ($) codes also catch beginning and end of line respectively.
3. Pattern
參閱此處
4. 應用
1) RegExp.exec(string)
Applies the RegExp to the given string, and returns the match information.
var match = /s(amp)le/i.exec("Sample text")
//match then contains ["Sample","amp"]
2) RegExp.test(string)
Tests if the given string matches the Regexp, and returns true if matching, false if not.
var match = /sample/.test("Sample text")
//match then contains false
3) String.match(pattern)
Matches given string with the RegExp. With g flag returns an array containing the matches, without g flag returns just the first match or if no match is found returns null.
var str = "Watch out for the rock!".match(/r?or?/g)
//str then contains ["o","or","ro"]
4) String.search(pattern)
Matches RegExp with string and returns the index of the beginning of the match if found, -1 if not.
var ndx = "Watch out for the rock!".search(/for/)
//ndx then contains 10
5) String.replace(pattern,string)
Replaces matches with the given string, and returns the edited string.
var str = "Liorean said: My name is Liorean!".replace(/Liorean/g,'Big Fat Dork')
//str then contains "Big Fat Dork said: My name is Big Fat Dork!"
6) String.split(pattern)
Cuts a string into an array, making cuts at matches.
var str = "I am confused".split(/\s/g)
//str then contains ["I","am","confused"]
Example:
var s='<div style="text-align:center;width:inherit;text-color:blue;">SOME TEXT</div>'
var rx=new RegExp("<div .*?>(.*?)</div>","i");
s=s.replace(rx,"$1");
// s="SOME TEXT"
// http://www.tek-tips.com/viewthread.cfm?qid=1231301