简体   繁体   中英

What is the best way to do split() in javascript and ignore blank entries?

I have the following C# code that i need to convert to javascript:

    static private string[] ParseSemicolon(string fullString)
    {
        if (String.IsNullOrEmpty(fullString))
            return new string[] { };

        if (fullString.IndexOf(';') > -1)
        {
            return fullString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(str => str.Trim()).ToArray();
        }
        else
        {
            return new[] { fullString.Trim() };
        }
    }

i see that javascript has a split() function as well but i wanted to see if there is built in support for the other checks or i have to do an additional loop around the array afterwards to "clean up" the data?

您可以使用过滤器 ,但此功能仅在更新的浏览器中实现。

"dog;in;bin;;cats".split(";").filter(function (x) { return x != ""; });

You can use a RegExp with a quantifier to split on any consecutive count of the delimiter:

var parts = input.split(/;+/);

Such as:

var input = "foo;;;bar;;;;;;;;;baz";
var parts = input.split(/;+/);

console.log(parts);
// [ "foo", "bar", "baz" ]

Try this

"hello;aamir;;afridi".split(';').filter(Boolean)

or

"hello;;aamir;;;;afridi".split(';').filter(Boolean)

results in

["hello", "aamir", "afridi"]

And to convert it back to string, use this

"hello;aamir;;afridi".split(';').filter(Boolean).join(' ')

or

"hello;aamir;;afridi".split(';').filter(Boolean).join(';')

Split also requires handling the empty results. However, where's another way

http://jsfiddle.net/9mHug/1/

var str = "aaa,bbb;ccc  ddd , eee";
var sp = str.match(/\w+/g);
alert(sp);

This will give you a clean array of only the words. \\w is a regex search that will find all letters of certain type [a-zA-Z0-9_]

Unfortunately javascript split() does not check for doublespaces etc, you would need to clean up your array later

var str = "How;are;;you;my;;friend?";
var arr = str.split(";");

alert(arr);

http://jsfiddle.net/p58qm/2/

You can then update the array with this loop

len = arr.length, i;

for(i = 0; i < len; i++ )
arr[i] && arr.push(arr[i]);  // copy non-empty values to the end of the array

arr.splice(0 , len);

alert(arr);

http://jsfiddle.net/p58qm/3/

Try this:

function parseSemicolon(fullString) {
    var result = new Array();
    if (!!fullString && fullString.length > 0) {
        fullString = fullString.trim();
        if (fullString.indexOf(';') > -1) {
            result = fullString.split(';');
            for (var i = 0; i < result.length; i++) {
                result[i] = result[i].trim();
            }
        } else {
            result = new Array(fullString);
        }
    }
    return result;
}

This should have exactly the same effect as your C# script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM