Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript split remove ":" colon character

Tags:

javascript

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",""]
like image 886
jas7 Avatar asked Dec 09 '22 23:12

jas7


2 Answers

Use 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

like image 96
Kendall Frey Avatar answered Dec 29 '22 01:12

Kendall Frey


Before parsing such string you should strip colons from the beginning and the end of the string:

a.replace(/(^:)|(:$)/g, '').split(":")
like image 26
valentinas Avatar answered Dec 29 '22 02:12

valentinas