Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS / TS splitting string by a delimiter without removing the delimiter

I have a string that I need to split by a certain delimiter and convert into an array, but without removing the delimiter itself. For example, consider the following code:

var str = "#mavic#phantom#spark";
str.split("#") //["", "mavic", "phantom", "spark"]

I need the output to be as follows:

["#mavic", "#phantom", "#spark"]

I read here but that does not answer my question.

like image 708
Alex Avatar asked Dec 28 '25 23:12

Alex


1 Answers

You could split by positive lookahead of #.

var string = "#mavic#phantom#spark",
    splitted = string.split(/(?=#)/);

console.log(splitted);
like image 78
Nina Scholz Avatar answered Dec 30 '25 12:12

Nina Scholz