0

I have been stucked with this problem for hours. I have a regex pattern and a matching string. Regarding to regex101.com, it is sure a matching string, but in my script, regarding to JSFiddle, it doesn't match.

RegExp: /\[img=?.*?http:\/\/lorempixel\.com\/640\/480.*?\/img\]/

String to match: [img=http://lorempixel.com/640/480]description[/img]

Script: JSFiddle

Can anyone find the problem here?

5
  • 1
    That's not how you build dynamic regex in JS, you need to use the RegExp constructor. Commented Jul 23, 2014 at 20:03
  • I have read somewhere (MDN or W3Schools), that strings convert to RegExp. Anyway, I am going to try your suggestion, thanks for the help. Commented Jul 23, 2014 at 20:05
  • Well, I tried it, aaaand, you are right! Thank you once again! @elclanrs Commented Jul 23, 2014 at 20:12
  • @helmet91 Just adding the RegExp constructor couldn't have fixed your problem. If it worked then you must have fixed the improper escaping in your string as well. Commented Jul 23, 2014 at 20:16
  • @JamesMontagne My original question aimed the RegExp constructor problem. However, as you said, I have another problem as well, but I don't want to ask too mutch. :D First, I am struggling with this new problem for another few hours. Commented Jul 23, 2014 at 20:44

1 Answer 1

2

You can't concatenate a regex using a regex literal, and you need a regex for the .match method.

var regex = new RegExp("\\[img=?.*?" + regexSafeUrl + ".*?\/img\\]");

http://jsfiddle.net/wue82/1/

EDIT: James Montague is correct that .match will implicitly use a RegExp. You don't need the / in the string that gets converted to RegExp though or these will be considered literal slashes. Your real problem was doing this as well as not properly escaping in the string.

http://jsfiddle.net/wue82/3/

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

2 Comments

If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). String.prototype.match
You missed one slash. The / before /img is still improperly escaped. Though it doesn't cause a problem since / doesn't need to be escaped at all.

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.