开发者

Javascript Regex Replace Text between Markers?

开发者 https://www.devze.com 2023-02-09 15:46 出处:网络
I have a start and end marker in ht开发者_如何转开发ml, I would like to replace the html between these markers with some other html. The expression below doesnt seem to work...

I have a start and end marker in ht开发者_如何转开发ml, I would like to replace the html between these markers with some other html. The expression below doesnt seem to work...

var myRegExp = new RegExp("<!-- " + "START IMPORTED HEAD.*?<!-- " + "END IMPORTED HEAD -->", "gi");
sHtmlContent = sHtmlContent.replace(myRegExp, "<!-- " + "INSERT_HEADER -->");

below is an example of the html block which appears in doc.

<!-- START IMPORTED HEAD -->
<style type="text/css">   
    input[type=button]
    {       
        padding-bottom: 3px;
    }        
</style>
<!-- END IMPORTED HEAD -->

any ideas would be great thanks


Manipulating the DOM is much better, but only if you have a browser. If you're doing server-side JavaScript (e.g. JS ASP) here's a way to do exactly what you asked:

var html = '<!-- START IMPORTED HEAD -->\n<style type="text/css">\n    input[type=button]\n    {\n        padding-bottom: 3px;\n    }\n</style>\n<!-- END IMPORTED HEAD -->';
var re   = new RegExp("<!-- " + "START IMPORTED HEAD[\\d\\D]*?<!-- " + "END IMPORTED HEAD -->", "gi");

html.replace(re, "<!-- " + "INSERT_HEADER -->");
// <!-- INSERT_HEADER -->

Your problem is that in JS the . character does not match newlines; using a [\d\D] character class instead matches all characters.


The problem are the newlines in your doc. Javascript does not support multiline (dot match all) matching out of the box. Either you remove the newlines first or you use an extension like XRegexp

See here: regexpal and then click the Dot matches all.


Using the DOM is a much more robust solution to your problem. Instead of using comment markers, just place that section of HTML inside a div with a known id:

<div id="foo">Original things</div>

With jQuery, you can do the replacement in a single line:

$('div#foo').html('Replaced things')

This will change the content of the div into:

<div id="foo">Replaced things</div>
0

精彩评论

暂无评论...
验证码 换一张
取 消