Javascript - How can I make this regex code global? -


i think missing 1 line somewhere, or need change 1 line. tried various /g methods think exec killing me here, maybe missing small easy addition, or maybe way have written flawed. saw lot of threads 1 mentioned while looping exec seemed infinite loop because including match in replacement.

here code got 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:

<span class='words'>the quick brown zad-14034 jumped on ead-14534</span> <span class='words'>the 13034 brown fox jumped on zen-12274</span> 

you define regex literal /expr/flags. regexp constructor used new regexp("expr", "flags"). thus, in case usage be:

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

at same time, gain no advantage of using constructor on literal, try using syntax:

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

reference:

update:

an attempt fix 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/


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -