[英]javascript regex replace html
see - > i have the following text in a variable 看到->我在变量中有以下文本
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>";
Now i want to append some data immediately after closing of <style
> tag's >
. 现在我想在
<style
>标签的>
关闭后立即添加一些数据。
Ex : 例如:
var mydata = "/n h1{a:b}/n";
So i want 所以我要
<style>/n h1{a:b}/n
it is very easy if there is no other attribute in style tag,but sometime there may be some other attributes like type
, id
如果style标签中没有其他属性,这很容易,但是有时可能会有其他一些属性,例如
type
, id
ex : 例如:
<style type="text/css" id="default_css_scope">
content
</style>
so that i cant use like this s.replace("<style>","<style>".mydata);
这样我就不能这样使用
this s.replace("<style>","<style>".mydata);
How can i do this with Regular Expression ? 我该如何使用正则表达式呢?
maybe you should try this. 也许您应该尝试一下。 i think it will solve your problem.
我认为它将解决您的问题。
str= str.replace("</style>",mydata+"</style>");
Caveat: I do not recommend using regular expressions to work extensively with HTML. 警告:我不建议使用正则表达式来广泛使用HTML。
But you might get away with it in this specific case: 但是在这种特定情况下,您可能会忽略它:
str = str.replace(/<style[^>]*>/, function(m) {
return m + mydata;
});
Kindly refer this. 请参考这个。 A Brilliant post from sometime ago on the use of Regex with HTML.
某段时间的一篇精彩文章,内容涉及正则表达式与HTML的结合使用。
Two of the most diverse technologies used together. 两种最多样化的技术一起使用。
[See here] RegEx match open tags except XHTML self-contained tags [查看此处] RegEx匹配除XHTML自包含标签之外的其他打开标签
Something like this 像这样
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.
Thanks to jAndy for his code snippit 感谢jAndy的代码片段
Hope this helps. 希望这可以帮助。
您可能需要研究HTML Agility Pack (免费库):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.