简体   繁体   English

Javascript-如何使此正则表达式代码全局化?

[英]Javascript - How can I make this regex code global?

I think I am missing one line somewhere, or need to change one line. 我想我某处缺少一行,或者需要更改一行。 I tried various /g methods but I think the exec is killing me here, maybe I am missing some small easy addition, or maybe the way I have written it is flawed. 我尝试了各种/ g方法,但我认为执行程序在这里杀死了我,也许我缺少一些简单的附加功能,或者我编写它的方式存在缺陷。 Saw a lot of threads where one mentioned while looping the exec but that seemed to infinite loop because I am including the match in the replacement. 看到很多线程在执行exec时提到了一个线程,但这似乎是无限循环的,因为我将匹配包含在替换中。

Here is the code I got so far 这是我到目前为止得到的代码

var system_url="http://somesite.com/";
$('.words').mouseover(function(){
  var re=new RegExp("[A-Z][A-Z][A-Z]-[0-9]{5}");
  var m=re.exec($(this).html());
  if (m == null) {
    re=new RegExp("[0-9]{5}");
    m=re.exec($(this).html());
    if (m == null) {}else{
      if ($(this).html().match("</a>")) {}else{
        tx=$(this).html().replace(m,"<a href='"+system_url+m+"' target='_blank' title='Ticket: "+m+"'>"+m+"</a>");
        $(this).html(tx);
      }
    }
  }else{
    if ($(this).html().match("</a>")) {}else{
      tx=$(this).html().replace(m,"<a href='"+system_url+m+"' target='_blank' title='Ticket: "+m+"'>"+m+"</a>");
      $(this).html(tx);
    }
  }
});

Some HTML Class: 一些HTML类:

<span class='words'>The quick brown ZAD-14034 jumped over the EAD-14534</span>
<span class='words'>The 13034 brown fox jumped over the ZEN-12274</span>

You define a regex literal as /expr/flags . 您将正则表达式文字定义为/expr/flags The RegExp constructor is used as new RegExp("expr", "flags") . RegExp构造函数用作new RegExp("expr", "flags") Thus, in your case the usage would be: 因此,在您的情况下,用法为:

new RegExp("[0-9]{5}", "g");

At the same time, you gain no advantage of using the constructor over a literal, so try using this syntax: 同时,相对于文字而言,使用构造函数没有任何好处,因此请尝试使用以下语法:

re = /[0-9]{5}/g;

Reference: 参考:

UPDATE: 更新:

An attempt to fix your code: 尝试修复您的代码:

var system_url = "http://somesite.com/";

$(".words").on("mouseover", function () {
    var $this = $(this);
    if (!$this.hasClass("replaced")) {
        var currentContent = $this.text();
        var re = /([A-Z]{3}-[0-9]{5})/g;
        var newContent = currentContent.replace(re, "<a href='" + system_url + "$1' target='_blank' title='Ticket $1'>$1</a>");
        $this.html(newContent);
        $this.addClass("replaced");
    }
});

DEMO: http://jsfiddle.net/5bJ5N/1/ 演示: http : //jsfiddle.net/5bJ5N/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM