0

I have a string as follows-

 roger::)

I need to split into two string as roger and :) . I am using the following

"roger::)".split(":")

But this forms three array elements,namely roger,[empty] and ) although what i need is two array elements as roger and :).

enter link description here

I tried using the following link but the console prints undefined for "roger::)".split(/_(.+)?/)[1]

Please Help.

Community
  • 1
  • 1
Mayur Buragohain
  • 1,566
  • 1
  • 22
  • 42

2 Answers2

1

Use lookaheads. It will split on a : if followed by :.

"roger::)".split(/:(?=:)/);

However perhaps this is what you want instead. Split on : unless it's a followed by ) which would be an happy face.

"roger::):another:test".split(/:(?!\))/);
plalx
  • 42,889
  • 6
  • 74
  • 90
  • `"roger::)".split(/:(?=:)/);` gives a single array element.However I wanted two array elements. – Mayur Buragohain Nov 08 '13 at 14:45
  • @MayurBuragohain I just pasted your code in the console and I get two elements? Which browser are you using? – plalx Nov 08 '13 at 14:50
  • i am using it for smiley itself.. testing across firefox,chrome.. `"roger::):another:test".split(/:(?!\))/);` refuses to accept anything except `:)` – Mayur Buragohain Nov 08 '13 at 14:56
  • @MayurBuragohain That's wierd. Works for me in FF and on http://gskinner.com/RegExr/ – plalx Nov 08 '13 at 15:15
  • @MayurBuragohain Could you post the result of `JSON.stringify("roger::):another:test".split(/:(?!\))/));` ? – plalx Nov 08 '13 at 15:19
0

Your test case looks limited, perhaps you can just use match:

'roger::)'.match(/[^:]+|:\)/g); // ['roger', ':)']

Maybe that suits, or not:

'roger::):another:test'.match(/[^:]+|:\)/g); // ["roger", ":)", "another", "test"]
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Could you confirm the second part of my answer is not working? It works for me, but in an old FF version and I cannot test in another browser right now. – plalx Nov 08 '13 at 15:10
  • Both statements in your answer return what I consider correct results in Safari 6.05 and Firefox 24, but testing in older browsers would be much more beneficial. I only suggested alternatives as they don't use look ahead so will suit older browsers. – RobG Nov 08 '13 at 21:49