티스토리 뷰

function RegMerge() {
    var expr = [];
    for ( var i = 0; i < arguments.length; i++ )
        expr.push( arguments[i].toString().replace(/^\/|\/\w*$/g, "") );
    return new RegExp( "(?:" + expr.join("|") + ")" );
}
var re = RegMerge( /Ninj(a|itsu)/, /Sword/, /Katana/ );
assert( re.test( "Ninjitsu" ),"Verify that the new expression works." );
assert( re.test( "Katana" ),"Verify that the new expression works." );

//The difference between a global and local search with match
var html = "
Hello world!
"; var results = html.match(/<(\/?)(\w+)([^>]*?)>/); assert( results[0] == "
", "The entire match." ); assert( results[1] == "", "The (missing) slash." ); assert( results[2] == "div", "The tag name." ); assert( results[3] == " class='test'", "The attributes." ); var all = html.match(/<(\/?)(\w+)([^>]*?)>/g); assert( all[0] == "
", "Opening div tag." ); assert( all[1] == "", "Opening b tag." ); assert( all[2] == "", "Closing b tag." ); assert( all[3] == "", "Opening i tag." ); assert( all[4] == "", "Closing i tag." ); assert( all[5] == "
", "Closing div tag." ); //Using the exec method to do both capturing and a global search var html = "
Hello world!
"; var tag = /<(\/?)(\w+)([^>]*?)>/g, match; var num = 0; while ( (match = tag.exec(html)) !== null ) { assert( match.length == 4,"Every match finds each tag and 3 captures." ); num++; } assert( num == 6, "3 opening and 3 closing tags found." ); //Using back-references to match the contents of an HTML tag. var html = "Hello world!"; var tag = /<(\w+)([^>]+)>(.*?)<\/\1>/g; var match = tag.exec(html); assert( match[0] == "Hello","The entire tag, start to finish." ); assert( match[1] == "b", "The tag name." ); assert( match[2] == " class='hello'", "The tag attributes." ); assert( match[3] == "Hello", "The contents of the tag." ); //Matching multiple words using a non-capturing group var re = /((?:ninja-)+)sword/; var ninjas = "ninja-ninja-sword".match(re); assert( ninjas[1] == "ninja-ninja-","Match both words, without extra capture." ); //A technique for compressing a query string. function compress(data) { var q = {}, ret = []; data.replace(/([^=&]+)=([^&]*)/g, function(m, key, value){ q[key] = (q[key] ? q[key] + "," : "") + value; return ""; }); for ( var key in q ) { ret.push( key + "=" + q[key] ); } return ret.join("&"); } assert( compress("foo=1&foo=2&blah=a&blah=b&foo=3") == "foo=1,2,3&blah=a,b", "Verify the compression." ); //trim function trim(str) { return str.replace(/^\s+|\s+$/g, ""); } function trim(str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } function trim(str) { var str = str.replace(/^\s\s*/, ''), ws = /\s/, i = str.length; while (ws.test(str.charAt(--i))); return str.slice(0, i + 1); } //unicode var str = "\u0130\u0131\u0132"; assert( ("#" + str).match(new RegExp("#([\\w\u0128-\uFFFF_-]+)")),"Verify that our RegExp matches a Unicode selector." );
저작자 표시
신고
댓글
댓글쓰기 폼