I'm having difficulty scanning for the special character "[". After looking around, I've tried:
var regEx = new RegExp(someValue + "[\x5B]"); // "5B" is the hex-value for "["
(I DO want case-sensitivity and I ONLY want the first occurrence so I intentionally didn't add any modifiers.)
I have been looking and looking, and I still have no idea what I'm doing wrong. If this is a bone-headed question, I'm sorry, but I'm new to JavaScript, and I'm still learning all the ins and outs.
function escapeRegExp(str) {
return str.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
var re = new RegExp(escapeRegExp(str));
See: Escape string for use in Javascript regex
var regEx = new RegExp(someValue + "\\[");
You simply have to escape it with a backslash. The backslash is double because it is a javascript special character as well.
Should be fine, if you just escape the character:
new RegExp(someValue + "\\[");
You need two backslashes because the backslash is the escape character for strings too. So \\[
will result in the string \[
which is what we need.
Both the regex .\[
and .[\x5B]
match the sub-string "e["
from the text:
"some[text"
as you can see yourself:
http://ideone.com/iR78l
var text = "some[text";
print(text.match(/.\[/));
and http://ideone.com/qvsCz
var text = "some[text";
print(text.match(/.[\x5B]/));
I think all you need is /[/ for your expression to find the first occurrence of "["
If there's something more complicated you're looking for, check out this tool: http://www.gskinner.com/RegExr/
It's a life-saver for creating regular expressions.
精彩评论