sertsedat
sertsedat

Reputation: 3600

Splitting the string with Regex yields unexpected result

I have the following string and regex

const message = "asdasd :+1::skin-tone-4:"
const emojiRegex = /(:[a-zA-Z0-9-_+]+:(:skin-tone-[1-6]:)?)/g

When I use .match(emojiRegex) on message, I get the following result which is correct:

[":+1::skin-tone-4:"]

But when I try to use .split(emojiRegex) with the same regex I get the following result:

["asdasd ", ":+1::skin-tone-4:", ":skin-tone-4:", ""]

I expect this as a result:

["asdasd ", ":+1::skin-tone-4:", ""]

What's wrong here? How should I change my regex to have the expected result?

const message = "asdasd :+1::skin-tone-4:"

const emojiRegex = /(:[a-zA-Z0-9-_+]+:(:skin-tone-[1-6]:)?)/g

console.log(message.match(emojiRegex));
console.log(message.split(emojiRegex));

Upvotes: 1

Views: 56

Answers (2)

Luca Kiebel
Luca Kiebel

Reputation: 10096

You have to remove the capturing group around :skin-tone-[1-6]:, as MDN says:

If separator is a regular expression that contains capturing parentheses (), matched results are included in the array.

const message = "asdasd :+1::skin-tone-4:"

const emojiRegex = /(:[a-zA-Z0-9-_+]+::skin-tone-[1-6]:?)/g

console.log(message.split(emojiRegex));

You could also use a non-capturing group (?)? and remove all elements from the result that are empty strings:

const message = "asdasd :+1::skin-tone-4:"
const message2 = "asdasd :+1:"


const emojiRegex = /(:[a-zA-Z0-9-_+]+:(?:skin-tone-[1-6]:)?)/g

console.log(message.split(emojiRegex).filter(Boolean));
console.log(message2.split(emojiRegex).filter(Boolean));

Upvotes: 2

Anurag Awasthi
Anurag Awasthi

Reputation: 6233

You shouldn't use capturing part in split regex. From mdn docs,

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array.

const message = "asdasd :+1::skin-tone-4:"

const emojiRegex = /(:[a-zA-Z0-9-_+]+::skin-tone-[1-6]:)/g


console.log(message.split(emojiRegex));

Upvotes: 1

Related Questions