js代码在html页面中转换成实体html编码的方法一:
<!DOCTYPE html>
<html>
<head>
<title>js代码转换成实体html</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="keywords" content="">
<script src="http://www.xueersi.com/lib/jQuery/1.11.1/jquery.min.js?1458897912"></script>
</head>
<body>
<textarea id="strs">
<div style="color:red">js代码转换成实体html--红</div>
<script>
function test(){
alert('测试红')
}
test();
</script>
<div style="color:green">js代码转换成实体html--绿</div>
<script type="text/javascript">
alert('测试绿')
</script>
</textarea>
<div id="scriptCode"></div>
<div>
直接在html页面写法是这样写即可:
方法一:
<script>
alert("测试");
</script>
</div>
<p>
方法二:
<script >
function test1(x,y){
return x+y ;
}
alert(test1(5,2))
</script>
</p>
</body>
</html>
<script type="text/javascript">
function htmlspecialchars(str){
/*//转换所有的html标签
str = str.replace(/</g, '<');
str = str.replace(/>/gi,'>');*/
//只转换js的script标签
str = str.replace(/<script/g, '<script');
str = str.replace(/<\/script>/gi,'</script>');
return str;
}
var str = $.trim($('#strs').val());
console.log(str)
console.log(htmlspecialchars(str))
$('#scriptCode').html(htmlspecialchars(str));
</script>