'How can I split a string but keep the delimiters in javascript?

I have searched online but it really doesnt make much sense.

I am trying to split a string and keep the delimiters too.

For example, I have this string:

var str = '45612+54721/121*124.2';

And, I would like to split it based on the operations & keep the operations.

So the output must look like this

[45612], [+], [54721], [/], [121], [*], [124.2];



Solution 1:[1]

If you use strings’ split with a regex, any captured groups become part of the resulting array.

var str = '45612+54721/121*124.2';
var tokens = str.split(/([+/*])/);
console.log(tokens);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1