1

I'm looking for a way to split a string in JavaScript dynamically and keep the contents after so many occurrences of a particular character. I've tried searching all over for something to solve this, though not had any success. Here's an example of the format I'll be using:

var s = "17:44, 22 July 2015 Foo connected to chat from address 127.0.0.1";

In the above example, I want the rest of the contents of the line after 2015, though at the same time I don't want to use 2015 or any of the start of the string as a hardcoded way to split because users can call themselves that, which would mess up the way of splitting, as well as I sometimes have to go back years too.

In a nutshell I want to split the string after the 4th space dynamically, and keep whatever is after without splitting the rest too.

ozank
  • 45
  • 6
  • [How to split a string after the nth occurence of a character?](http://stackoverflow.com/questions/19293872/how-to-split-a-string-after-the-nth-occurence-of-a-character) –  Jul 22 '15 at 17:15

2 Answers2

2

Do matching instead of splitting.

> var s = "17:44, 22 July 2015 Foo connected to chat from address 127.0.0.1";
> s.match(/^((?:\S+\s+){3}\S+)\s+(.+)/)
[ '17:44, 22 July 2015 Foo connected to chat from address 127.0.0.1',
  '17:44, 22 July 2015',
  'Foo connected to chat from address 127.0.0.1',
  index: 0,
  input: '17:44, 22 July 2015 Foo connected to chat from 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 to chat from address 127.0.0.1'

OR

var s = "17:44, 22 July 2015 Foo connected to chat from address 127.0.0.1";
alert(s.match(/^(?:\S+\s+){3}\S+|\S.*/g))
  • ^(?:\S+\s+){3}\S+ would match the first four words.
  • | OR
  • \S matches the first non-space character from the remaining string.
  • .* greedily matches all the remaining characters.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Thanks for your explanation and examples, very useful, did exactly what I wanted :) – ozank Jul 22 '15 at 17:35
  • What if I want to keep the date as a single split? The Output I need is `"17:44 22 July 2015, Foo connected to chat from address 127.0.0.1"` – Muhammad Usman Jan 25 '16 at 06:27
1

Split, slice and join for resovle issue

function splitter(string, character, occurrences) {
  var tmparr = string.split(character); // split string by passed character, it returns Array
  return tmparr.slice(occurrences, tmparr.length).join(" "); // slice returns a shallow copy of a portion of an Array into a new Array object. And finally join() - joins all elements of an array into a string.
}

var s = "17:44, 22 July 2015 Foo connected to chat from address 127.0.0.1";

alert(splitter(s, ' ', 4))
Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47