Razgriz
Razgriz

Reputation: 7343

Splitting a string using a JavaScript regex but keeping the delimiter?

I'm receiving input like:

F12T213B1239T2F13T341F324

and I have to group it by letter followed by the numbers that follows it. So the ideal output would be:

F12,T213,B1239,T2,F13,T341,F324

And then do some processing on the numbers based on the letter that they're with. The letters are fixed, they are always B,F,T

So far, I've tried to split it by letter with:

var separators = ['T', 'B', 'F'];
var parts = input.split(new RegExp('('+separators.join('|')+')'),'g');

But the problem with this is that I end up with just the numbers, I need the letters with them.

Does anyone know how to split a string by certain characters but still keep the characters in the output?

Upvotes: 2

Views: 3931

Answers (4)

cнŝdk
cнŝdk

Reputation: 32145

Instead of using .split() you can use .match() with a matching group in the regex, it will give you an array of all your wanted matches.

This is the regex you need /([TBF]\d{1,4})/g.

This is how should be your code:

var input = "F12T213B1239T2F13T341F324";
var separators = ['T', 'B', 'F'];
var parts = input.match(new RegExp('(['+separators.join('')+']\\d{1,4})','g'));

console.log(parts);

Note:

  • The ['+separators.join('')+'] will give you the following [TBF], in your regex so it matches one of the separators.
  • And \d{1,4} will match the digits following that separator.

Demo:

var input = "F12T213B1239T2F13T341F324";
var separators = ['T', 'B', 'F'];
var parts = input.match(new RegExp('(['+separators.join('')+']\\d{1,4})','g'));

console.log(parts);

Upvotes: 0

Krzysztof Mazur
Krzysztof Mazur

Reputation: 608

var str = "F12T213B1239T2F13T341F324";
var regex = /(?=T)|(?=F)|(?=B)/g;
console.log(str.split(regex));

Solution is based on Positive lookahead

Upvotes: 4

Taha Paksu
Taha Paksu

Reputation: 15616

You can do it with a noncapturing group and some empty value filtering.

The regex is : ((?:F|T|B)\d+)

Here's a working code:

console.log(
    "F12T213B1239T2F13T341F324"
        .split(/((?:F|T|B)\d+)/g)
        .filter(d => d != "")
);

Upvotes: 0

Sweeper
Sweeper

Reputation: 270995

One way to do this is to replace all the FTBs with a space followed by that letter:

regex: [FTB]
replacement:  $0 // note the leading space

Then, you can split it with space characters.

Upvotes: 1

Related Questions