[英]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.