I have a string like this.
var a="1:2:3:";
I want to split it with a.split(":")
to remove the ":" colon character.
I want to get this as the result:
["1","2","3"]
But instead the result of a.split(":")
is this:
["1","2","3",""]
I have a string like this.
var a="1:2:3:";
I want to split it with a.split(":")
to remove the ":" colon character.
I want to get this as the result:
["1","2","3"]
But instead the result of a.split(":")
is this:
["1","2","3",""]
Share
Improve this question
edited Jul 4, 2012 at 0:19
user142162
asked Jul 4, 2012 at 0:15
jas7jas7
3,0756 gold badges25 silver badges36 bronze badges
1
- Split does exactly what the name implies... in this case it split 3 and null. Remove the last colon – rlemon Commented Jul 4, 2012 at 0:17
3 Answers
Reset to default 11Use this trim method to remove the trailing colon.
function TrimColon(text)
{
return text.toString().replace(/^(.*?):*$/, '$1');
}
Then you can call it like this:
TrimColon(a).split(":")
If you wanted to you could of course make TrimColon
a string prototype method, allowing you to do something like this:
a.TrimColon().split(":");
In case you'd like an explanation of the regex used: Go here
Before parsing such string you should strip colons from the beginning and the end of the string:
a.replace(/(^:)|(:$)/g, '').split(":")
If you don't want to do it with RegEx as in the other answers, you can choose the one below and use it.
Only remove empty strings
["1","2","3",""].filter(String)
// ['1', '2', '3']
["1","2","3","", 123].filter(String)
// ['1', '2', '3', 123]
["1","2","3","", 123, null, undefined].filter(String)
// ['1', '2', '3', 123, null, undefined]
// Function
function RemoveEmptyString(arr) {
if (Array.isArray(arr))
return arr.filter(String);
else
return [];
}
RemoveEmptyString(["1","2","3",""])
// ["1","2","3"];
// Prototype
Object.defineProperty(Array.prototype, 'removeEmptyStrings', {
value: function () {
return this.filter(String);
}
});
["1","2","3", ""].removeEmptyStrings()
// ["1","2","3"]
Only remove unvalid elements
["1","2","3",""].filter(Value => Value)
// ['1', '2', '3']
["1","2","3","", 123].filter(Value => Value)
// ['1', '2', '3', 123]
["1","2","3","", 123, null, undefined].filter(Value => Value)
// ['1', '2', '3', 123]
// Function
function RemoveEmptyString(arr) {
if (Array.isArray(arr))
return arr.filter(Value => Value);
else
return [];
}
RemoveEmptyString(["1","2","3","", 123, null, undefined])
// ["1","2","3", 123]
// Prototype
Object.defineProperty(Array.prototype, 'removeEmptyStrings', {
value: function () {
return this.filter(Value => Value);
}
});
["1","2","3","", 123, null, undefined].removeEmptyStrings()
// ["1","2","3", 123]