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,T
Solution 1:
var str = "F12T213B1239T2F13T341F324";
var regex = /(?=T)|(?=F)|(?=B)/g;
console.log(str.split(regex));
Solution is based on Positive lookahead
Solution 2:
One way to do this is to replace all the FTB
s with a space followed by that letter:
regex: [FTB]
replacement: $0// note the leading space
Then, you can split it with space characters.
Solution 3:
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 != "")
);
Solution 4:
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(newRegExp('(['+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(newRegExp('(['+separators.join('')+']\\d{1,4})','g'));
console.log(parts);
Post a Comment for "Splitting A String Using A Javascript Regex But Keeping The Delimiter?"