0

This is my string

 var str = "Here is some &text:also , here is &another:one"
 var myRegExp = /\b\s(\&){1}(\w)+(\:){1}(\w)+\s?\b/g
 str.match(myRegExp)
 //[" &text:also", " &another:one"]

Works as expected till now, the problem is with the splitting

str.split(myRegExp)

Expectations: ["Here is some" , ", here is"]
Reality ["Here is some", "&", "t", ":", "o", " , here is", "&", "r", ":", "e", ""]

What could be the reason for this ? I can extract my required array by looping over and splitting at the matches, isnt there any shortcut apart from that ?

2
  • Why are you escaping a colon? Commented Dec 5, 2012 at 11:21
  • Oh that works w/o escaping too thanks for the info, I was being careful Commented Dec 5, 2012 at 11:25

2 Answers 2

2

This is because the regex engine is also including the group values into the result..use (?:)

So the regex to split would be

/\b\s(?:\&){1}(?:\w)+(?:\:){1}(?:\w)+\s?\b/g

Or there is no need of grouping it at all

/\b\s\&{1}\w+\:{1}\w+\s?\b/g
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need the groupings or the {1} in the regex. Use:

var myRegExp = /\b\s&\w+:\w+\s?\b/g

1 Comment

I just posted a raw example, my actual regex has grouping though but for the given example groupings messed up the split, Thanks for the correction

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.