0

I am using a regex for getting some pattern data and it is working fine but I need to use some part of regex from a variable but I am unable to do that please help me if somebody know how to make it.

var subStr = document_root.documentElement.outerHTML.match(/http(.*?Frover.fff.com.*?)\;/g);
alert(subStr[0]);

I get first result in alert but need to do it like this.

var link=rover.fff.com;
var regexpattern="/http(.*?F"+link+".*?)\;/g"
var rex=new RegExp(regexpattern);
var subStr = document_root.documentElement.outerHTML.match(regexpattern);
alert(subStr[0]);

I don't get anything. Please help me. Comment if you confuse in anything.

A.A Noman
  • 5,244
  • 9
  • 24
  • 46
anshul
  • 31
  • 5
  • NB: Applying regex on HTML is in most cases a bad idea. – trincot Nov 28 '17 at 17:32
  • Please describe what the purpose is of your code: do you want to find hyperlinks? What if they appear in text, or in an attribute that is not a `href`, or in an HTML comment, .... – trincot Nov 28 '17 at 17:34
  • That close reason is really a bad one. This question should be resolved without regular expressions. – trincot Nov 28 '17 at 17:45
  • [Mozilla has an entire documentation page dedicated to regex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions). It's definitely a good read if you're beginner – ctwheels Nov 28 '17 at 17:52
  • @trincot you're correct, but the duplicate was chosen because it answers **why** the OP is having the issues they're experiencing. – ctwheels Nov 28 '17 at 17:56
  • @trincot Perhaps a better question such as https://stackoverflow.com/questions/3871358/get-all-the-href-attributes-of-a-web-site would be better suited for the actual content portion of this question, but based on the title, I think Wiktor chose the correct duplicate. – ctwheels Nov 28 '17 at 17:59
  • these links are available in some bad format in hidden div so i need to use regex.I have no other option – anshul Nov 28 '17 at 18:40

1 Answers1

1

In JavaScript, when you need to use a variable, you have to create a new RegExp object, as you've tried.

It takes two parameters. The first is a string of the pattern (without the slashes at the start and end). The second is any flags (like your g).

So, your pattern would be something like this:

var regexpattern = new RegExp('http(.*?F' + link + '.*?)\\;', 'g')

Note, that you have to escape any special characters in the string like you would any other string (in this case, your \ had to be escaped to \\ so it'll work properly).

After that, you use it the same as the /pattern/ form. In your case, be sure to use rex, not regexpattern in your match() function.

(If so some reason that wasn't a literal \ and you were escaping the semi-colon, just remove it completely, you won't need to escape a semi-colon.)

samanime
  • 25,408
  • 15
  • 90
  • 139