-1

I'm trying to create a dynamic regex to select URL's based on a segment or the whole URL.

For example, I need to get var.match(/http:\/\/www.something.com\/something/)

The text inside the match() needs to be converted so that special characters have \ in front of them such for example "\/". I was not able to find a function that converts the URL to do this? Is there one?

If not, what characters require a \ in front?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
ama2
  • 2,611
  • 3
  • 20
  • 28
  • So you're looking for a JavaScript regular-expression escape function, and/or for what characters are meaningful inside a JS regex? – Dave Newton Jun 19 '12 at 00:43
  • 2
    The list is `[.?*+^$[\]\\(){}|-]` From http://stackoverflow.com/questions/2593637/how-to-escape-regular-expression-in-javascript – Ruan Mendes Jun 19 '12 at 00:44

2 Answers2

2

I use this to escape a string when generating a dynamic regex:

var specials = /[*.+?|^$()\[\]{}\\]/g;
var url_re = RegExp(url.replace(specials, "\\$&"));
Trevor
  • 9,518
  • 2
  • 25
  • 26
0

( ) [ ] ? * ^ $ \ . + | and in your case, / since you're using that as the delimiter in the match.

Further info mostly to pre-empt comments and downvotes: I don't really know where - come from as a special character. It's only special when inside character class brackets [ and ] which you're already escaping. If you want to include characters that are sometimes special (which the OP doesn't) that would include look-ahead/behind characters as well, which include =, < and >.

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • @minitech in JS? I know in grep they must actually be given a preceding `\\` to do anything, I think it's egrep in which they do not. – djechlin Jun 19 '12 at 02:50
  • `j{1,5}` matches 1-5 instances of `j`. No, it does not need a preceding ``\``, at least in JavaScript, nor in any other language I've ever used... are you thinking of a different usage for `{}`? – Ry- Jun 19 '12 at 02:52
  • Same usage. Regular old `grep` does this silly thing where they count as normal and putting a backslash in front gives them special meaning. Perl might do this? I can't remember. I came up with the list I posted from remembering that 1) in Perl there are 12 dirty characters and 2) they're all very basic regex constructs. – djechlin Jun 19 '12 at 02:58