Làm thế nào trim zero (số 0) ở trước một string number trong JS

(2 versions - English and Vietnamese)

Tiếng Việt

Nếu bạn có một number kiểu tring bắt đầu với các số 0 đằng trước. Example 001, 002, 01, …. Bạn muốn xóa nó đi? Oke, sẽ có rất nhiều cách để làm điều đó:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var strNumber = "0010";

// 1. sử dụng parseInt function
parseInt(strNumber, 10);

// 2. sử dụng toán tử +
+strNumber;

// 3. sử dụng Number object
Number(strNumber);

// 4. sử dụng regex (biểu thức chính quy)
strNumber.replace(/^0+/, ''); // replace trả về một string, nhưng đã cắt đi số 0 ở đầu

// kết quả
// 10

Lưu ý:

  • Số 10 ở tham số thứ 2 function parseInt nó gọi là radix, thường thì mọi người nghĩ mặc định nó là 10 nhưng không phải đa số trình duyệt nghĩ vậy. Nên cần truyền vào để work solid. Bạn đọc thêm link tham khảo bên dưới để biết thêm thông tin về nó.
  • ^0+ trong regex nghĩa là bắt đầu chuỗi là 0 và tìm tất cả 0 liền kề nhau trong chuỗi.

Tham khảo

ENGLISH version

If you have a string number with leading zero. Example 001, 002, 01, …. How to remove it? In this simple post, I’ll show you how can we do that. Let’s go.

There are a lot of ways to do that:

1
2
3
4
5
6
7
8
9
10
11
12
13
var strNumber = "001";

// 1. using parseInt function
parseInt(strNumber, 10);

// 2. using + operator
+strNumber;

// 3. using Number object
Number(strNumber);

// 4. using regex
strNumber.replace(/^0+/, '');

Note:

  • With parseInt function 10 we call it’s the radix (an integer between 2 and 36 that represents the radix - the base in mathematical numeral systems, of the string). In this case, we need to tranforms from a string number to a real number, so we will pass 10. Read refer link below to more information.
  • ^ in regex that means, find in the string with leading zero.
  • 0+ means, find all zero nearby.

Refer

 Comments
Comment plugin failed to load
Loading comment plugin