#101 解析字串

完成一个 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值