Javascript split remove ":" colon character

I have a line like this.

var a="1:2:3:"; 

I want to split it into a.split(":") to remove the colon character ::

I want to get this as a result:

 ["1","2","3"] 

But instead, the result of a.split(":") is as follows:

 ["1","2","3",""] 
+4
source share
2 answers

Use this cropping method to remove the back colon.

 function TrimColon(text) { return text.toString().replace(/^(.*?):*$/, '$1'); } 

Then you can call it like this:

 TrimColon(a).split(":") 

If you want, you can of course make the TrimColon string prototype method, allowing you to do something like this:

 a.TrimColon().split(":"); 

If you need an explanation of the regular expression used: http://bit.ly/Ol8lsX

+10
source

Before parsing such a line, you must separate the colons from the beginning and end of the line:

 a.replace(/(^:)|(:$)/g, '').split(":") 
+4
source

All Articles