How to dynamically split a string using JavaScript/jQuery after so many occurences of a character -
i'm looking way split string in javascript dynamically , keep contents after many occurrences of particular character. i've tried searching on solve this, though not had success. here's example of format i'll using:
var s = "17:44, 22 july 2015 foo connected chat address 127.0.0.1";
in above example, want rest of contents of line after 2015, though @ same time don't want use 2015 or of start of string hardcoded way split because users can call that, mess way of splitting, have go years too.
in nutshell want split string after 4th space dynamically, , keep whatever after without splitting rest too.
do matching instead of splitting.
> var s = "17:44, 22 july 2015 foo connected chat address 127.0.0.1"; > s.match(/^((?:\s+\s+){3}\s+)\s+(.+)/) [ '17:44, 22 july 2015 foo connected chat address 127.0.0.1', '17:44, 22 july 2015', 'foo connected chat address 127.0.0.1', index: 0, input: '17:44, 22 july 2015 foo connected chat address 127.0.0.1' ] > s.match(/^((?:\s+\s+){3}\s+)\s+(.+)/)[1] '17:44, 22 july 2015' > s.match(/^((?:\s+\s+){3}\s+)\s+(.+)/)[2] 'foo connected chat address 127.0.0.1'
or
var s = "17:44, 22 july 2015 foo connected chat address 127.0.0.1"; alert(s.match(/^(?:\s+\s+){3}\s+|\s.*/g))
^(?:\s+\s+){3}\s+
match first 4 words.|
or\s
matches first non-space character remaining string..*
greedily matches remaining characters.
Comments
Post a Comment