javascript - jQuery replace Start and End tag in html document -
javascript - jQuery replace Start and End tag in html document -
i have next jquery snippet should replace code such [button] text here [/button] like:
<a class="button">text here</a>
the javascript have following:
$(document).ready(function() { var buttonstart = $("body").html().replace(/\[button\]*/ig,'<a class="button">'); $("body").html(buttonstart); var buttonend = $("body").html().replace(/\[\/button\]*/ig,'</a>'); $("body").html(buttonend); });
the problem having keeps replacing other elements on page have nil tags [button] [/button]. insance following:
<div id="middlebarleft"></div>
also gets replaced into
<a class="button"><div id="middlebarleft"></div></a>
shouldn't regex have above [button] , [/button] tags?
also, there other efficient way go this?
thanks
=====================
update.. entire html file replaces elements have nil want replace
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script type='text/javascript'> $(document).ready(function() { var buttonstart = $("body").html().replace(/\[button\]/ig,'<a class="button">'); $("body").html(buttonstart); var buttonend = $("body").html().replace(/\[\/button\]/ig,'</a>'); $("body").html(buttonend); }); </script> <style> li{ list-style:none; padding-top:10px; padding-bottom:10px;} .button, .button:visited { background: #222 url(overlay.png) repeat-x; display: inline-block; padding: 5px 10px 6px; color: #fff; text-decoration: none; -moz-border-radius: 6px; -webkit-border-radius: 6px; -moz-box-shadow: 0 1px 3px rgba(0,0,0,0.6); -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.6); text-shadow: 0 -1px 1px rgba(0,0,0,0.25); border-bottom: 1px solid rgba(0,0,0,0.25); position: relative; cursor: pointer } </style> </head> <body> <div> <ul> <li>[button]test[/button]</li> <li></li> <li>sample text</li> </ul> </div> </body> </html>
the problem stems way replacement occurs - please consider next fiddle: http://jsfiddle.net/gyrya/
as can see there 2 buttons in end, though there's 1 [button][/button] statement - it's because first you're replacing [button] <a class='button'>
creates unmatched tag. causes </a>
added @ end. you're replacing [/button] </a>
, creates unmatched tag - time <a>
, @ end.
a improve solution this: http://jsfiddle.net/gyrya/1/
edit: http://jsfiddle.net/gyrya/2/ omit script tag matching
edit 2: http://jsfiddle.net/gyrya/5/ - final solution, incorporating @rain diao non-greedy matching
edit 3: added performance test cases: http://jsperf.com/eithed-rsc3, please read give-and-take below @rain diao's reply genesis of it
javascript jquery html jquery-plugins
Comments
Post a Comment