2013-05-13 125 views
5

I'm trying to use JQuery to achieve the following logic:與<a href> tags in Javascript/JQuery

  • Replace the string value of [url="http://www.google.com"]Google[/url] with <a href="http://www.google.com">Google</a>

Please see my HTML page below. The problem is that on pressing the button, the orignal text is just pasted and no RegEx replacements are made.

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>Test</title> 
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
    <script type="text/javascript"> 
     //<![CDATA[ 
     function processJs() { 
      var oldtext = $("#oldtext").html(); 
      var newtext = oldtext.replace('\[url\s?=\s?"?(.*?)"?\](.*?)\[\/url\]', '<a href="$1">$2</a>'); 
      $('#mydiv').html(newtext); 
     } 
     //]]> 
    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <div id="oldtext"> 
      Try this funky new search engine: 
      [url="http://www.google.com"]Google[/url] 
      Or this older one from back in the day: 
      [url="http://uk.altavista.com"]AltaVista[/url] 
     </div> 
     <div> 
      <input type="button" id="btn" value="Replace" onclick="processJs(); return false;" /> 
     </div> 
     <div id="mydiv" style="background-color: #eeeeee; border: 2px inset #aaaaaa"> 
      Replaced text will go here. 
     </div> 
    </form> 
</body> 
</html> 

I've had this RegEx pattern work using ASP.NET, so I'm not sure where the problem lies when ported to JavaScript...

回答

5

That is not a valid regex. Use / as modifiers:

/\[url\s?=\s?"?(.*?)"?\](.*?)\[\/url\]/ 

making the function:

function processJs() { 
    var oldtext = $("#oldtext").html(); 
    var newtext = oldtext.replace(/\[url\s?=\s?"?(.*?)"?\](.*?)\[\/url\]/g, '<a href="$1">$2</a>'); 
    $('#mydiv').html(newtext); 
} 

g at the end will repeat it over the text. Here is a fiddle: http://jsfiddle.net/xe2F9/

+0

令人驚歎。回答太快,以至於StackOverflow甚至不允許我再接受7分鐘:-D – EvilDr 2013-05-13 15:03:34

4
var newtext = oldtext.replace(/\[url\s?=\s?"?(.*?)"?\](.*?)\[\/url\]/g, '<a href="$1">$2</a>'); 

更換的[url]標籤您指定「搜索」作爲一個正則表達式對象 - 不是一個字符串。

只需使用/.../將自動創建一個透明。

+1

請問後面的/ g是什麼? – EvilDr 2013-05-13 15:00:26

+1

@EvilDr它意味着匹配所有(這是JS特定的) – HamZa 2013-05-13 15:00:45

+1

'因爲你想替換所有的匹配,而不僅僅是第一個。 – barryhunter 2013-05-13 15:01:04