javascript - jQuery - RegEx working bizarrely -


i new regexp. here problem. have input value. apply regexp "rule" input value. rule starts input value , not case sensitive. lets take example. reference string paris (75018) , input value pari. in scenario working fine. if input value paris (7 not working. in case "system" telling me no match , don't it. matching! hope can help. thank in advance replies. cheers. marc.

http://jsfiddle.net/ju8va/

my html:

<input id="btn" type="submit" />​ 

my js:

$('#btn').click(function() {     var loc = "paris"; //input value...     var locregexp = new regexp("^" + loc, "i"); //       var test = "paris (75018)"; //reference value      if (test.match(locregexp)) {         alert('matches');         }         else {             alert('does not match');         }     });​ 

the problem ( has special meaning in regular expressions. literally, have escape \(. see here: http://jsfiddle.net/ju8va/1/

var loc = "paris \\(7"; var locregexp = new regexp("^" + loc, "i"); 

note there double backslash; that's because backslash has special meaning in literal quoted strings, have escape backslash literally in regex.

also note literal (unquoted) regexes, don't need escape backslash, parenthesis. example: test.match(/paris \(7/).

in regular expressions, unescaped ( means "start capture group". capture groups way retrieve match data after running it. see here answer how work: http://www.regular-expressions.info/brackets.html

if don't know ahead of time loc contain, can replace instances of parenthesis escaped versions, this:

var locregexp = new regexp("^" + loc.replace(/\(/g, "\\(").replace(/\)/g, "\\)"), "i"); 

but aware there many special characters besides parenthesis may need test for. if find replacing lot of characters, maybe consider trying different approach. example, looking case-insensitive search starts @ beginning of test string? don't need regular expressions, can substring search:

test.tolowercase().indexof(loc.tolowercase()) === 0 

Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -