Created
December 11, 2008 18:53
-
-
Save swdyh/34819 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" | |
"http://www.w3.org/TR/html4/loose.dtd"> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> | |
<script src="http://code.jquery.com/jquery-latest.js"></script> | |
<script type="text/javascript" src="http://jqueryjs.googlecode.com/svn/trunk/qunit/testrunner.js"></script> | |
<link rel="stylesheet" href="http://dev.jquery.com/view/trunk/qunit/testsuite.css" type="text/css" media="screen" /> | |
<!-- | |
<script type="text/javascript" src="testrunner.js"></script> | |
<link rel="stylesheet" href="testsuite.css" type="text/css" media="screen" /> | |
--> | |
<script type="text/javascript" src="regexp_safe.js"></script> | |
</head> | |
<body> | |
<h1>QUnit test</h1> | |
<h2 id="banner"></h2> | |
<h2 id="userAgent"></h2> | |
<ol id="tests"></ol> | |
<div id="main"></div> | |
</body> | |
</html> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function regExpSafe(str) { | |
try { | |
new RegExp(str) | |
return str | |
} | |
catch(e) { | |
return regExpEscape(str) | |
} | |
} | |
// http://snipplr.com/view/9649/escape-regular-expression-characters-in-string/ | |
function regExpEscape(str) { | |
var sp = new RegExp('[.*+?|()\\[\\]{}\\\\]', 'g') | |
return str.replace(sp, '\\$&') | |
} | |
// qunit test | |
$(document).ready(function(){ | |
test('regExpEscape', function() { | |
equals(regExpEscape('. .'), '\\. \\.') | |
equals(regExpEscape('* *'), '\\* \\*') | |
equals(regExpEscape('+ +'), '\\+ \\+') | |
equals(regExpEscape('? ?'), '\\? \\?') | |
equals(regExpEscape('| |'), '\\| \\|') | |
equals(regExpEscape('[ ['), '\\[ \\[') | |
equals(regExpEscape('] ]'), '\\] \\]') | |
equals(regExpEscape('( ('), '\\( \\(') | |
equals(regExpEscape(') )'), '\\) \\)') | |
equals(regExpEscape('{ {'), '\\{ \\{') | |
equals(regExpEscape('} }'), '\\} \\}') | |
equals(regExpEscape('\\ \\'), '\\\\ \\\\') | |
equals(regExpEscape('. * + ?'), '\\. \\* \\+ \\?') | |
}) | |
test('regExpSafe', function() { | |
equals(regExpSafe('foo'), 'foo') | |
equals(regExpSafe('foo*hoge+'), 'foo*hoge+') | |
equals(regExpSafe('foo(hoge'), 'foo\\(hoge') | |
equals(regExpSafe('( [ {'), '\\( \\[ \\{') | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment