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?
You can use filter, but this function is implemented only in more recent browsers.
"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(';')
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With