在Javascript中用分隔符的单个出现(不是两次)拆分字符串 [英] Split string with a single occurence (not twice) of a delimiter in Javascript

查看:114
本文介绍了在Javascript中用分隔符的单个出现(不是两次)拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用示例可以更好地解释这一点。我希望实现这样的拆分:

This is better explained with an example. I want to achieve an split like this:

两个单独的令牌 - 这个 - 只是 - 一个 - 令牌 - 另一个

- >

[two ,分开,代币,这 - 只是 - 一个 - 代币,另一个]

我天真地试过 str.split(/ - (?! - )/)并且它不会匹配第一次出现的双分隔符,但它会匹配第二个(因为它没有跟着分隔符):

I naively tried str.split(/-(?!-)/) and it won't match the first occurrence of double delimiters, but it will match the second (as it is not followed by the delimiter):

[two,separate,tokens,this-, is-,just-,one - ,token,another]

我有更好的选择吗?比循环遍历字符串?

Do I have a better alternative than looping through the string?

顺便说一下,下一步应该是将两个连续的分隔符替换为一个,这样就可以通过重复分隔符来转义分隔符。 ..所以最终的结果是这样的:

By the way, the next step should be replacing the two consecutive delimiters by just one, so it's kind of escaping the delimiter by repeating it... So the final result would be this:

[两个,分开,令牌,这是 - 只是-one-token,另一个]

如果只能在一个这应该真的很棒!

If that can be achieved in just one step, that should be really awesome!

推荐答案

鉴于正则表达式与边缘情况不太一样(如连续5次)分隔符)我不得不处理用单个分隔符替换双分隔符(然后它会变得棘手,因为'----'。replace(' - ',' - ')给出'---'而不是' - '
I写了一个循环遍历字符的函数,并且一次性完成所有操作(虽然我担心使用字符串累加器可能很慢:-s)

Given that the regular expressions weren't very good with edge cases (like 5 consecutive delimiters) and I had to deal with replacing the double delimiters with a single one (and then again it would get tricky because '----'.replace('--', '-') gives '---' rather than '--') I wrote a function that loops over the characters and does everything in one go (although I'm concerned that using the string accumulator can be slow :-s)

f = function(id, delim) {
    var result = [];
    var acc = '';
    var i = 0;
    while(i < id.length) {
        if (id[i] == delim) {
            if (id[i+1] == delim) {
                acc += delim;
                i++;
            } else {
                result.push(acc);
                acc = '';
            }
        } else {
            acc += id[i];
        }
        i++;
    }

    if (acc != '') {
        result.push(acc);
    }

    return result;
    }

和一些测试:

> f('a-b--', '-')
["a", "b-"]
> f('a-b---', '-')
["a", "b-"]
> f('a-b---c', '-')
["a", "b-", "c"]
> f('a-b----c', '-')
["a", "b--c"]
> f('a-b----c-', '-')
["a", "b--c"]
> f('a-b----c-d', '-')
["a", "b--c", "d"]
> f('a-b-----c-d', '-')
["a", "b--", "c", "d"]

(如果最后一个标记为空,则意味着跳过它)

(If the last token is empty, it's meant to be skipped)

这篇关于在Javascript中用分隔符的单个出现(不是两次)拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆