0

I shouldn't say I actually have a "problem" (the code seems to... work? Although one time it through an error in the console possibly due to environmental reasons), but I'm picking apart a piece of code and I see this:

key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

"key" is passed into the function containing this line. As you might expect, it's a string that's ultimately used as the needle in a haystack.

It's sanitizing something, but I can't figure out what it's sanitizing (primarily because I don't have any fluency in regex I guess). JSLint is barking about something also (Unexpected ']') but I think it's a false positive because it's not parsing the regex.

Wasn't sure to ask this at Stack Overflow or at Code Review, but it's not really "review" so here it is.

Any insight from you regexy type people would be much appreciated.

1
  • Are you sure it's for the jQuery tag and not for the javascript tag ? Commented Apr 23, 2012 at 14:40

2 Answers 2

5

If I got it right it replaces [ with \[ and ] with \], so basically an escaping of square brackets.

Sign up to request clarification or add additional context in comments.

1 Comment

Would love to know a good way of doing it... that should go without saying... ;-)
1

These all do the same thing (globally)

var key = 'a[b] [c] [][]d'.replace(/[\[]/g,"\\\[").replace(/[\]]/g,"\\\]"); 
print(key);
var key = 'a[b] [c] [][]d'.replace(/[\[]/g,'\\[').replace(/[\]]/g,'\\]'); 
print(key);
var key = 'a[b] [c] [][]d'.replace(/([\[\]])/g,"\\$1"); 
print(key);

1 Comment

Useful! Not sure I want to print out to my printer, but I know what you meant. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.