I am very new to RegExp. Here is my problem. I have an input value. I apply a RegExp “rule” to that input value. The rule is starts with the input value and is not case sensitive. Lets take an example. My reference string is Paris (75018) and my input value is Pari. In that scenario everything is working fine. But if the input value is Paris (7 it is not working. In that case the “system” is telling me no match and I don’t get it. It is matching! Hope someone can help. Thank you in advance for your replies. Cheers. Marc.
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 is the
(has a special meaning in regular expressions. To get it literally, you have to escape it as\(. See here: http://jsfiddle.net/JU8Va/1/Note that there is a double backslash; that’s because backslash itself has a special meaning in literal quoted strings, so you have to escape the backslash to get it literally in the regex.
Also note that for literal (unquoted) regexes, you don’t need to escape the backslash, just the parenthesis. For example:
test.match(/Paris \(7/).In regular expressions, an unescaped
(means “start a capture group”. Capture groups are the way you retrieve match data after running it. See here for an answer about how those work: http://www.regular-expressions.info/brackets.htmlIf you don’t know ahead of time what
locwill contain, you can replace all instances of parenthesis with the escaped versions, like this:But be aware that there are many special characters besides parenthesis that you may need to test for. If you find yourself replacing a lot of characters, maybe consider trying a different approach. For example, are you just looking for a case-insensitive search that starts at the beginning of the test string? For that you don’t need regular expressions, you can just do a substring search: