我是javascript的新手,我正在尝试解析日志并过滤掉一些东西。日志看起来像:
v=5,ci=3,si=60,sv=1,ss=active,es=-,ai=a23-369b-4da3-b2da-630aee75f8c5,ip='99.114.107.39',rm=GET,rv=HTTP/1.1,rs=200,rt=0.787020,rr='/tag/febe1eab436e98eb4ed3711870496c91/st.js?l=http%3A%2F%2Fwww.michaels.com%2Fv
应该通过逐行分割,
来打印输出,并过滤掉我不需要的内容。例如,我只需要ip
和rr
属性,因此输出应如下所示:
ip='99.114.107.39'
rr='/tag/febe1eab436e98eb4ed3711870496c91/st.js?l=http%3A%2F%2Fwww.michaels.com%2Fv
我的代码如下,但它不起作用:
<!doctype html>
<html>
<head>
<title>reading file</title>
<script>
function readText(obj){
var file = obj.files[0],
div=document.getElementById('main');
if(file){
div.innerHTML='';
var reader = new FileReader();
reader.onerror = function(event){
div.innerHTML='The file can\'t be read! Error ' + event.target.error.code;
}
reader.onload = function(event){
var cont = event.target.result.split(',');
for(var i=0; i<cont.length; i++){
var name = cont.split('=');
if (name[0]==="rr") {
div.innerHTML+=cont[i]+'<br />';
}
}
}
reader.readAsText(file);
}
}
window.onload=function(){
document.getElementById('ff').onchange=function(){readText(this);}
}
</script>
</head>
<body>
<input type="file" id="ff" />
<div id="main"></div>
</body>
</html>
答案 0 :(得分:0)
使用javascript的split()
:
示例:强>
window.onload = function () {
var text = "v=5,ci=3,si=60,sv=1,ss=active,es=-,ai=a23-369b-4da3-b2da-630aee75f8c5,ip='99.114.107.39',rm=GET,rv=HTTP/1.1,rs=200,rt=0.787020,rr='/tag/febe1eab436e98eb4ed3711870496c91/st.js?l=http%3A%2F%2Fwww.michaels.com%2Fv";
var ip = '',
rr = '';
var splits = text.split(',');
for (var i = 0; i < splits.length; i++) {
if (splits[i].indexOf('ip') > -1)
ip = splits[i];
else if (splits[i].indexOf('rr') > -1)
rr = splits[i];
}
document.getElementById('divIp').innerHTML = ip;
document.getElementById('divRr').innerHTML = rr;
};