Reputation:
I convert english numbers to arabic numbers with this function :
export const e2p = (num) => {
return num.replace(/\d/g, (d) => '۰۱۲۳۴۵۶۷۸۹'[d]);
};
In component :
import { e2p } from '../../e2p';
{e2p(JSON.stringify(127000))}
It works fine and it gives me this result :
۱۲۷۰۰۰
Now I want to have a separator after three numbers but don't know how like this :
۱۲۷,۰۰۰
How can I have a separator after three numbers in javascript ?
Upvotes: 0
Views: 141
Reputation: 20910
You can add another regex to insert a ,
every 3 digits before end:
replace(/(.)(?=(?:.{3})+$)/g, '$1,')
const e2p = (num) => {
return num.replace(/\d/g, (d) => '۰۱۲۳۴۵۶۷۸۹'[d])
.replace(/(.)(?=(?:.{3})+$)/g, '$1,');
};
console.log(e2p(JSON.stringify(127000)));
console.log(e2p(JSON.stringify(1278000)));
(.)
match any character, captures it in group 1(?=(?:.{3})+$)
lookahead, if the next sequence ends with 3 * n
characters, replace it with $1,
(whatever captured in group 1 and followed by a ,
)Also, there's a built-in way to do it. Check Number#toLocaleString
const e2p = number => number.toLocaleString('ar-EG');
console.log(e2p(127000));
console.log(e2p(1278000));
Upvotes: 3