JS regular in surveying (assertions) - digital thousand separators

Introduce lookahead  (? = ...)  and lookbehind (<= ...?) 
To facilitate the people do not want to see a long article, so if the integer can be used in support ES2018 environment:

String(12345678).replace(/(?<=\d)(?=(\d{3})+\b)/g, ',') // "12,345,678"

 

One of the most critical is certainly lookahead (? = ...), also known as zero-width positive lookahead assertion .
Add thousand separators trouble spot that only digits from right to left and in front of a multiple of 3 Digital Intermediate need to add a comma
and a positive match is from left to right, this time you need to use the order certainly look around.
Looking around do not take characters that can be matched to meet the requirements of the position
, such as, `/ Java (? = Script ) /` will only match there behind Java Script characters

'Java or JavaScript'.replace(/Java(?=Script)/, 'Type'); // "Java or TypeScript"

 

We know that three consecutive matching method is a digital / \ d {3} / digit number is a multiple of 3 / (\ d {3})
+ / recombination sequence certainly look around, we will be able to match behind in front of the position of a multiple of 3 bits / (? = (\ d {

3}) +) / we will half the battle, the following problem is ' 123456 ' such 6 bits, the foregoing does not need to add separator.
So we also need to match the numbers in front of the location, which requires affirmative lookbehind / / (<= \ d?
) Lookbehind and lookahead contrary, is behind the designated position mode such as:

'Adding subscripts using Javascript'.replace(/(?<=Java)script/, 'Script'); // "Adding subscripts using JavaScript"

 

The above two together can be matched to the digital front, and the position of the back of a multiple of 3, but if you write like this:

String(12345678).replace(/(?<=\d)(?=(\d{3})+)/g, ','); // "1,2,3,4,5,678"

Find and different expectations, the last three digits in front of the right side of each number added a comma.
We can use the word delimiters `\ b` to solve this problem

String(12345678).replace(/(?<=\d)(?=(\d{3})+\b)/g, ',') // "12,345,678"

 

If you are running in that environment to support ES2018 here on it, but there are many browsers do not support lookbehind. Fortunately, we can be a little flexible, do not use lookbehind to solve

String(12345678).replace(/(\d{1,3})(?=(\d{3})+\b)/g, '$1,') // "12,345,678"


For convenience you can add a function

function formatNumber(number) {
    if (typeof number !== 'number') {
        throw new Error('formatNumber parameter must be number');
    }
    if (Number.isNaN(number)) {
        return '0';
    }
    let result;
    const [integerNum, decimalNum] = String(number).split('.');
    return integerNum.replace(/(\d)(?=(\d{3})+\b)/g, '$1,') + (decimalNum ? `.${decimalNum}` : '');
}

 

If you want to use the domestic habits, divide by ten thousand, to change the 3 to 4

Guess you like

Origin www.cnblogs.com/liyan-web/p/12079923.html