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.

1

2 Answers 2

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(/:(?!\))/);
Sign up to request clarification or add additional context in comments.

5 Comments

"roger::)".split(/:(?=:)/); gives a single array element.However I wanted two array elements.
@MayurBuragohain I just pasted your code in the console and I get two elements? Which browser are you using?
i am using it for smiley itself.. testing across firefox,chrome.. "roger::):another:test".split(/:(?!\))/); refuses to accept anything except :)
@MayurBuragohain That's wierd. Works for me in FF and on gskinner.com/RegExr
@MayurBuragohain Could you post the result of JSON.stringify("roger::):another:test".split(/:(?!\))/)); ?
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"]

2 Comments

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.
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.

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.