Nathan Campos
Nathan Campos

Reputation: 29497

Problems With JavaScript And Regular Expressions

I'm trying to get the YouTube link and get just it's Id(which is working nice). I'm trying to make a function to detect if the text entered is a URL or just the Id. Like this:

function youtube_do(video, width, height) {
  var make_syntax;
  var regexp_url;

  regexp_url = /((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)/;

  if(regexp_url.test(video) = false) {
    make_syntax = embed_format(youtube_id_extract(video), width, height);
  } else {
    make_syntax = embed_format(video, width, height);
  }

  document.writeln(make_syntax);
}

And executing it like this:

<script type="text/javascript" src="js/YouTube.js"></script>

<h1>YouTube Example</h1>
<script type="text/javascript">
youtube_do("http://www.youtube.com/watch?v=VMl_71dqeR8", "640", "390");
</script>

When I try that in the browser I got nothing, so I started to debug and I got this errors:

YouTube.js:22 - SyntaxError: Parse error
YouTube.htm:5 - ReferenceError: Can't find variable: youtube_do

Where 22 is the exactly line of the if statement. What should I do to correct this?

Upvotes: 2

Views: 417

Answers (4)

sokratisg
sokratisg

Reputation: 81

To avoid any future hassle regarding regex validation why don't you check it against an online tester ? http://www.macfh.co.uk/JavaJive/ProgScriptWeb/JSRETest.html

For more urls just google :)

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838376

A few points:

1) Your regular expression is invalid because it contains slashes. This will give an error. You need to escape the slashes.

2) The {1} in your regular expression is redundant - if you don't specify a quantifier then {1} is implied. This doesn't give an error, but for clarity you should omit it.

3) It is not necessary to escape : in a regular expression. This doesn't give an error, but unnecessary escaping decreases readability, so you should remove the unnecessary backslashes.

4) You have unnecessary parentheses in your regular expression. This doesn't give an error but it makes it more difficult to read, so they should be removed.

After these changes this line looks like this:

regexp_url = /(mailto:|(news|(ht|f)tps?):\/\/)\S+/;

5) Also the operator = performs an assignment. This will give an error. You should use if (!...) instead:

if (!regexp_url.test(video))

Upvotes: 4

Rudu
Rudu

Reputation: 15892

Line 22 should read:

if(regexp_url.test(video) === false) {

= Is for value assignment.
== Compares values with type-conversion.
=== Compares both value and type.

You could also rewrite line 22 as:

if(!regexp_url.test(video)) {

Upvotes: 3

Oscar Godson
Oscar Godson

Reputation: 32726

You need to do regexp_url.test(video) == false not regexp_url.test(video) = false :)

Upvotes: 1

Related Questions