Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split the string from backward

I want to split string into array with fix number of char but the counting should be from backwards. In the following example I want to split the string into array with set of 3 char:

InputString = '1234567'

Wanted:

OutputArray= [1,234,567]

Tried:

InputString.match(/.{1,3}/g)
OutputArray = [123,456,7]
like image 626
Bhagwan Thapa Avatar asked Apr 11 '26 19:04

Bhagwan Thapa


1 Answers

Use String#match with positive lookahead assertion regex.

var InputString = '1234567';

console.log(
  InputString.match(/\d{1,3}(?=(\d{3})*$)/g)
)

Regex explanation here.


With String#split method with positive lookahead assertion for asserting position to split.

var InputString = '1234567';

console.log(
  InputString.split(/(?=(?:\d{3})+$)/)
)

Regex explanation here.

like image 115
Pranav C Balan Avatar answered Apr 14 '26 11:04

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!