且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript和正则表达式的问题

更新时间:2022-11-14 19:15:26





正则表达式中的 {1} 是多余的 - 如果您不要指定量词,则隐含{1}。这不会导致错误,但为了清楚起见,您应该省略它。



3)不需要转义在正则表达式中。这不会导致错误,但不必要的转义会降低可读性,所以您应该删除不必要的反斜杠。



4)在正则表达式中有不必要的括号。这不会产生错误,但会使读起来更加困难,因此应该将其删除。



在这些更改后,此行如下所示:

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

5)运算符 = 执行分配。这会给出错误。您应该使用 if(!...)代替:

  if (!regexp_url.test(video))


I'm trying to get the *** 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 ***_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(***_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/***.js"></script>

<h1>*** Example</h1>
<script type="text/javascript">
***_do("http://www.***.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:

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

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

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))