简体   繁体   English

替换样式内容javascript HTML

[英]Replace STYLE content javascript HTML

I have a JavaScript variable: 我有一个JavaScript变量:

var s =   
 "<html><head><style>body{a:b;c:d}</style></head><body></body></html>";

First, I am extracting the content inside <style> tags: 首先,我提取<style>标记内的内容:

s = s.split(/(<style[^>]*>|<\/style>)/i)[2]; 

// s == "body{a:b;c:d}";

Then I am doing something with s and after the manipulation I need to append it on <style> tags. 然后我用s做一些操作,在操作之后,我需要将其附加到<style>标记上。

How can I insert s between <style> and </style> ? 我怎样才能插入s之间<style></style>

Example: Modified var s = "body{x:h;f:l;}"; 示例:修改后的var s =“ body {x:h; f:l;}”;

so I need the resulting content like this: 所以我需要这样的结果内容:

 "<html><head><style>body{x:h;f:l;}</style></head><body></body></html>";

Update : jQuery is allowed - But only string manipulation is allowed. 更新 :允许使用jQuery-但仅允许字符串操作。 Pure JavaScript solutions have first priority. 纯JavaScript解决方案具有最高优先级。

var s  = "<html><head><style>body{a:b;c:d}</style></head><body></body></html>";
var b = s.split(/(<style[^>]*>|<\/style>)/i)[2]; 
s = s.replace(b,"body{x:h;f:l;}");

finally, s is what you want. 最后,s是您想要的。

Does this work for you: 这对您有用吗:

var s  ="body{a:b;c:d}";
    var newS = s.replace("body{a:b;c:d}", "body{x:h;f:l;}");
    alert(s);
    alert(newS);

Use below mentioned code 使用下面提到的代码

var someHTML = "<html><head><style>body{a:b;c:d}</style></head><body></body></html>";
var styleContents = someHTML.split(/(<style[^>]*>|<\/style>)/i)[2];
document.getElementById('style').innerHTML = styleContents;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM