我有这个字符串,包含2个警告和3个错误,每个警告/错误由它的开始warning:
或error:
及其结尾_
符号决定:
var data="warning:No data found_error:There's no data to display_error:Too many connections_warning:Test not passed:please check spelling_error:Connection lost";
如何让jQuery分别提取每个错误和警告?在这样的结构上:
if (data.indexOf("warning:") >= 0){
var warnings.="<p class='warning'>"+EACHWARNINGHERE+"</p>";}
因此变量警告会存储此值:
var warnings="
<p class='warning'>No data found</p>
<p class='warning'>Test not passed:please check spelling</p>"
答案 0 :(得分:2)
使用拆分:
var data="warning:No data found_error:There's no data to display_error:Too many connections_warning:Test not passed:please check spelling_error:Connection lost";
var a = data.split('warning:');//first split by `warning:`
var c = [];
var warnings = '';
for(var i in a){
var b = a[i].split('error:');//now every part split again but by `error:`
if(b[0]){
warnings += "<p class='warning'>"+b[0].replace(/_$/,'')+"</p>";
}
}
现在warnings
是:
<p class='warning'>No data found</p>
<p class='warning'>Test not passed:please check spelling</p>
答案 1 :(得分:0)
拆分'_'然后检查句子是否以'warning:'或'error:'
开头var sentences = data.split('_')
for (var i=0; i<sentences.length; i++) {
ver sentence = sentences[i];
var sentenceType = data.slice(0,data.indexOf(':'));
var sentenceText = sentence.slice(data.indexOf(':')+1);
if (sentenceType == 'warning') {
// add warning element with sentenceText
}
else {
// add error element
}
}