我想读取插入到textarea中的行并返回值大于0.0的行 - 这是我输入textarea的行的示例:
error: there were errors found during runtime 12.0
warning: incorrect info 1.0
warning: file at 'C://localhost/myfiles' not found 0.0
warning: file at 'C://localhost/css' not found 0.0
warning: file at 'C://localhost/js' not found 0.0
warning: file at 'C://localhost/assets' not found 5615612.0
这些将是线条的例子 应该返回的值是因为最后的数字大于0.0
error: there were errors found during runtime 12.0
warning: incorrect info 1.0
warning: file at 'C://localhost/assets' not found 5615612.0
每行的代码
foreach(explode("\n", $text) as $line) {
//read line
}
,并尝试使用Javascript
var lines = $('textarea').val().split('\n');
for(var i = 0;i < lines.length;i++){
//code here using lines[i] which will give each line but how do I look
//for the last numbers to make sure that the numbers are grater than 0.0
}
答案 0 :(得分:3)
在javascript中,您可以从一个过滤行
的函数开始var endsAboveZero = function(line) {
var words = lines.split(/\s/);
var last = words[words.length - 1];
return parseFloat(last) > 0;
};
然后您可以根据此过滤您的行。如果您可以使用Array.filter
:
var lines = $('textarea').val().split('\n');
var goodLines = lines.filter(endsAboveZero);
或者,使用for循环:
var lines = $('textarea').val().split('\n');
var goodLines = [];
for (var i = 0; i < lines.length; i++) {
if (endsAboveZero(lines[i])) {
goodLines.push(lines[i]);
}
}
如果textarea中存在奇数输入,您可能需要添加一些错误检查。
答案 1 :(得分:1)
使用Xufox建议的过滤器(检查为null,因为它会导致错误“无法读取null的属性'0')
function getLines()
{
return $("textarea").val().split("\n").filter(line => line.match(/\d+\.\d+$/) != null && Number(line.match(/\d+\.\d+$/)[0]) > 0);
}
$(document).ready(
function(){
$('#printlogs').html(getLines().join('<br>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea style="width:100%;height:120px">
error: there were errors found during runtime 12.0
warning: incorrect info 1.0
warning: file at 'C://localhost/myfiles' not found 0.0
warning: file at 'C://localhost/css' not found 0.0
warning: file at 'C://localhost/js' not found 0.0
warning: file at 'C://localhost/assets' not found 5615612.0
</textarea>
<h4>Error Log</h4>
<printlogs id="printlogs"></printlogs>