2

I have a regex which looks like this:

[@|#](.*?)\s

What I basically want is, split matching regex into arrays.

So I use the following code:

var testString = "Hi this is a test @info@test.com and @martin we have to go."
console.log(testString.split(/(\@|\#)(.*?)\s/));

The result what I get looks like this:

["Hi this is a test ", "@", "info@test.com", "and ", "@", "martin", "we have to go."]

What I actually want is:

["Hi this is a test ", "@info@test.com", "and ", "@martin", "we have to go."]

https://regex101.com/r/yJf9gU/1

https://jsfiddle.net/xy4bgtmn/

2 Answers2

2

Don't use split, use match:

testString.match(/[@#]\S+|[^@#]+/g)
// ["Hi this is a test ", "@info@test.com", " and ", "@martin", " we have to go."]

This regex simply matches all non-spaces after an @ or a #, or it matches all non-@ or # characters, effectively splitting it into chunks.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
2

You could use split by placing [#@] inside the capture group followed by matching 1+ non whitespace chars ([#@]\S+)

let s = "Hi this is a test @info@test.com and @martin we have to go.";
console.log(s.split(/([#@]\S+)/));
The fourth bird
  • 154,723
  • 16
  • 55
  • 70