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.

1

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your explanation and examples, very useful, did exactly what I wanted :)
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"
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))

1 Comment

can you add some explanation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.