javascript - How to split a string by a character not directly preceded by a character of the same type? -


let's have string: "we.need..to...split.asap". split string delimiter ., wish split first . , include recurring .s in succeeding token.

expected output:

["we", "need", ".to", "..split", "asap"] 

in other languages, know possible look-behind /(?<!\.)\./ javascript unfortunately not support such feature.

i curious see answers question. perhaps there clever use of look-aheads presently evades me?

i considering reversing string, re-reversing tokens, seems work after... plus controversy: how reverse string in place in javascript?

thanks help!

here's variation of the answer guest271314 handles more 2 consecutive delimiters:

var text = "we.need.to...split.asap"; var re = /(\.*[^.]+)\./; var items = text.split(re).filter(function(val) { return val.length > 0; }); 

it uses detail if split expression includes capture group, captured items included in returned array. these capture groups thing interested in; tokens empty strings, filter out.

edit: unfortunately there's perhaps 1 slight bug this. if text split starts delimiter, included in first token. if that's issue, can remedied with:

var re = /(?:^|(\.*[^.]+))\./; var items = text.split(re).filter(function(val) { return !!val; }); 

(i think regex ugly , welcome improvement.)


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -