Regex get only full matching (Not grouping)

Viewed 34

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 Answers

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.

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+)/));

Related