[英]javascript regex replace html
看到->我在變量中有以下文本
var s =
"<html>
<head>
<style type="text/css" >
body{
background:url(/a.png);
}
</style>
<script src="2.js"></script>
<script src="1.js"></script>
</head>
<body >
{BODYCONTENT}
</body>
</html>";
現在我想在<style
>標簽的>
關閉后立即添加一些數據。
例如:
var mydata = "/n h1{a:b}/n";
所以我要
<style>/n h1{a:b}/n
如果style標簽中沒有其他屬性,這很容易,但是有時可能會有其他一些屬性,例如type
, id
例如:
<style type="text/css" id="default_css_scope">
content
</style>
這樣我就不能這樣使用this s.replace("<style>","<style>".mydata);
我該如何使用正則表達式呢?
也許您應該嘗試一下。 我認為它將解決您的問題。
str= str.replace("</style>",mydata+"</style>");
警告:我不建議使用正則表達式來廣泛使用HTML。
但是在這種特定情況下,您可能會忽略它:
str = str.replace(/<style[^>]*>/, function(m) {
return m + mydata;
});
像這樣
var start = html.indexOf("<script", 0); //find the index of the first script
start = html.indexOf(">", start); //Starting for that script tag, find the next >
var output = [html.slice(0, start), myData, html.slice(start)].join(''); //Add string to at that position.
感謝jAndy的代碼片段
希望這可以幫助。
您可能需要研究HTML Agility Pack (免費庫):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.