user2316602
user2316602

Reputation: 642

Javascript - Regexp - Global search Issue

I have got little issue. I have got this:

var result1=content.match("/<a [^>]*href\s*=\s*[\"']([^>\"']*)[\"'][^>]*>/gi")[1];

This code gives nothing. I'm sure that input and Regex are right, but:

  1. It gives me an error : Cannot read property 1 of null.
  2. When I remove [1] then result1 = null and also it's not array.

Any idea what is wrong?

Upvotes: 0

Views: 389

Answers (2)

mishik
mishik

Reputation: 10003

You're trying to pass regex as a string:

content.match("/<a [^>]*href\s*=\s*[\"']([^>\"']*)[\"'][^>]*>/gi")[1];

should be

content.match(/<a [^>]*href\s*=\s*[\"']([^>\"']*)[\"'][^>]*>/gi)[1];

Example:

> a = "abc"
"abc"
> a.match("/abc/")
null
> a.match(/abc/)
["abc"]

Following m.buettner's comment. If you need to build a regex from string use this syntax:

var my_regex = new RegExp("abc", "gi");

Upvotes: 2

dfsq
dfsq

Reputation: 193311

Remove quotes around regexp or use new RegExp constructor. It should be:

var result1 = content.match(/<a [^>]*href\s*=\s*[\"']([^>\"']*)[\"'][^>]*>/gi);

http://jsfiddle.net/wGWEt/1/

Using RegExp constructor:

var result1 = content.match(RegExp("<a [^>]*href\s*=\s*[\"']([^>\"']*)[\"'][^>]*>", "gi"));

http://jsfiddle.net/wGWEt/2/

Upvotes: 2

Related Questions