完成一个 extractStr
函数,可以把一个字符串中所有的 :
到 .
的子串解析出来并且存放到一个数组当中,例如:
extractStr('My name is:Jerry. My age is:12.') // => ['Jerry', '12']
注意,:
和 .
之间不包含 :
和 .
。也即是说,如果 ::abc..
,则返回 ['abc']
。
(本题来源:《JavaScript Cookbook》)
const extractStr = (str) => {
const result = [];
let index = 0; // 判断是否结束循环
while(index < str.length) {
//pos1定位:的位置,pos2定位.的位置
let pos1 = str.indexOf(':', index);
if(pos1 == -1) {
break;
}
let pos2;
while(str.indexOf('.', index) < pos1) {
if(str.indexOf('.', index) == -1) {
break;
}
pos2 = str.indexOf('.', index);
index = pos2 + 1;
}
if(str.indexOf('.', index) > pos1) {
pos2 = str.indexOf('.', index);
}
else {
break;
}
index = pos2 + 1;
//判断pos1与pos2之间是否还存在:?
let pos3 = pos1;
while((str.indexOf(':', pos3 + 1) != -1) && (str.indexOf(':', pos3 + 1) < pos2)) {
pos3 = str.indexOf(':', pos3 + 1);
}
result.push(str.substring(pos3 + 1, pos2));
}
return result;
}
之后看到网上一位大神写的AC代码,感觉自愧不如:
const extractStr = (str) => /* TODO */
{
let result = [];
let targets = str.split(".").slice(0, -1);
targets.forEach(target=>{
let position = target.lastIndexOf(":");
if( position >= 0){
result.push(target.substring(position + 1));
}
});
return result;
}